当前位置:  开发笔记 > 编程语言 > 正文

JavaScript:hasOwnProperty vs dot语法

如何解决《JavaScript:hasOwnPropertyvsdot语法》经验,为你挑选了1个好方法。

想象一下有一个对象: foo = {"bar": 1}

使用hasOwnProperty点语法来检查对象bar内的属性是否有任何好处foo:

if (foo.hasOwnProperty('bar') {
  // do something
}

VS

if (foo.bar) {
  // do something
}

也:

将hapen什么,如果foo["bar"]undefined

怎么样foo undefined

Alexander T... 11

看看这个例子,

Object.prototype.baz = 100;
var foo = {"bar": 1}

// will be false because in foo object there is no baz property 
// hasOwnProperty checks that the object has the specified property 
// and does not check that property in the prototype chain
if (foo.hasOwnProperty('baz')) {
  console.log('foo.hasOwnProperty("baz")');
}


//  will be true because baz property will be found 
//  in parent object through prototype chain
if (foo.baz) {
  console.log('foo.baz');
}



1> Alexander T...:

看看这个例子,

Object.prototype.baz = 100;
var foo = {"bar": 1}

// will be false because in foo object there is no baz property 
// hasOwnProperty checks that the object has the specified property 
// and does not check that property in the prototype chain
if (foo.hasOwnProperty('baz')) {
  console.log('foo.hasOwnProperty("baz")');
}


//  will be true because baz property will be found 
//  in parent object through prototype chain
if (foo.baz) {
  console.log('foo.baz');
}
推荐阅读
郑谊099_448
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有