JavaScript 里 in 运算符继承属性的问题

var o = new Object();

o.OwnProperty('toString')  // false

'toString' in o   // true

里这句

'toString' in o

这句为何会返回 true?

阅读 4.4k
3 个回答

obj.hasOwnProperty判断某属性是“自身属性”还是“继承自原型对象的属性”;
in操作符判断的是该对象的某属性是否存在且可枚举;

我觉得你不应该奇怪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是只要在对象内的属性都会检查。

这个toString方法是从Object对象继承来的,@merb_tu 说的对

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题