gpt4 book ai didi

javascript - angular.isBoolean 的实现?

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:58 25 4
gpt4 key购买 nike

我正在审查一些源代码,并且仅针对 _.isBoolean 函数包含了下划线/lodash。 underscore source如下:

_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};

查看Function components in ng我看到类似的函数(angular.isObjectangular.isStringangular.isNumber 等),但没有angular.isBoolean 函数。

angular.js源代码有一个内部函数(下面的源代码),但是一个请求公开的问题(feat: register isBoolean as a public member of global angular #5185)被关闭说“下划线和 lodash 等其他库很好地解决了这些问题”。

function isBoolean(value) {
return typeof value === 'boolean';
}

问题:

  • 我最初的 react 是复制 isBoolean 并在我的代码中创建一个命名函数,但哪种实现更正确?
  • 我使用下划线版本是为了与 future 的升级兼容吗?
  • 我认为将我的实现“鸭打”到 angular.isBoolean 中是个坏主意吗?

最佳答案

I was reviewing some source code and underscore/lodash was included just for the _.isBoolean function. […] My initial reaction was to convert isBoolean to a local function

是的,好主意(如果您强调只是)。甚至可能不是一个函数,而是简单地内联它。

but which implementation is more correct?

当对象是 Boolean class 的实例时,它们的行为不同被传入。您正在审查的应用程序中会发生这种情况吗?可能不会。如果是,只有您知道是否要将它们视为 bool 值。

除此之外,val === true || val === falsetypeof val == "boolean" 具有相同的效果。

I assume it is a bad idea to "duck punch" my implementation into angular.isBoolean?

angular 不太可能会这样做,因此您几乎不会引发碰撞。不过,问问自己:它真的有用吗?其他代码会使用它吗?有关更多讨论,请查看 Don't modify objects you don't own .

关于javascript - angular.isBoolean 的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com