关于javascript:为什么lodash的.isObject和.isPlainObject的行为与” typeof x ===’object'”不同?

Why do lodash's .isObject, .isPlainObject behave differently than “typeof x === 'object'”?

请考虑以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var o1 = {}
var O = function () {
  return this
}
var o2 = new O()
var o3 = function() {}
var o4 = [o1, o1]

var output = [
    [_.isObject(o1), _.isObject(o2), _.isObject(o3), _.isObject(o4)],
    [_.isPlainObject(o1), _.isPlainObject(o2), _.isPlainObject(o3), _.isPlainObject(o4)],
    [typeof o1 === 'object', typeof o2 === 'object', typeof o3 === 'object', typeof o4 === 'object'],
    [o1 instanceof Array, o2 instanceof Array, o3 instanceof Array, o4 instanceof Array]
]

/* outputs:

[
    [true,true,true,true],
    [true,false,false,false],
    [true,true,false,true],
    [false,false,false,true]
]

*/

很明显,我们可以看到.isObject()

之间存在断开连接

Which checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(' ')

.isPlainObject()

Which if value is a plain object, that is, an object created by the Object constructor or one with a Prototype of null

和我们的好朋友'x2>。

我有三个问题:

  • 是否有一个自觉的设计决策,以使.isObject.isPlainObject的行为不同于本机.js类型检查?
  • 如果我的第一个问题是正确的,那么设计决定是什么,以这种方式进行的好处是什么?
  • 是否有任何行为与typeof x === 'object'完全相同的本地lodash(或underscore.js)is*函数?
  • 很明显,我可以继续使用typeof,但是在某些地方使用一个或另一个语法有点奇怪,例如,在检查typeof x === 'object' && typeof x !== 'function'时使用.isObject会返回假阳性。我真的看不到.isFunction已经存在时.isObject函数返回true的任何好处。


    typeof与某物是否为对象无关。函数,字符串和{}具有不同的typeof,它们都是对象。函数当然是一流的对象,就像字符串是一流的对象一样,因此isObject对于字符串和对象必须返回true。

    记录中涉及以下内容:

    Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))

    哇!没有方便的isObject方法,这确实需要测试。公平地说,大多数将typeof返回为object,但是高级方法(尤其是在lodash之类的库中)的要点是,程序员可以忽略这些废话。

    如果您关心typeof参数,请使用typeof。如果您关心不是函数的对象,则有两种选择:可以使用typeof并专门检查字符串,或者可以使用isObject && !isFunction。我希望后者。后者确实恰好说出了您要传达的内容,因此编码确实是正确的事情。如果您认为当说"对象"时暗含的不是函数,那么您就不认为函数是一类对象,或者您希望您的代码更类似于它们所用的语言。不是。但是,您不能责怪lodash是一个广泛使用函数是一流对象这一事实的库,从而使语言成为函数是一流对象的语言更具表现力。

    我相信这是您大部分的问题。我相信isPlainObject的用例是回答问题"这仅仅是数据吗?"还是"这是代码吗?",所以创建为伪类(某些东西的new)的对象不会计数。


    n


  • lodash文档将Lodash描述为" JavaScript实用程序库,可提供一致性,模块化,性能,