var o = new Object();
o.OwnProperty('toString') // false
'toString' in o // true
里这句
'toString' in o
这句为何会返回 true?
黄舟2017-04-10 14:44:52
我觉得你不应该奇怪in
,反而应该奇怪hasOwnPropery
吧。不信你运行o.hasOwnProperty('hasOwnProperty')
试试。关于这个MDN上不是已经讲的很详细了么:
Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.
Object.prototype.hasOwnProperty
所以你可以这么理解:hasOwnProperty
是检查自己真正拥有的属性,不检查继承的属性;而in
是只要在对象内的属性都会检查。