JavaScript:hasOwnProperty vs dot语法

时间:2015-12-07 08:07:04

标签: javascript hasownproperty

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

使用hasOwnProperty优于dot-syntax来检查bar对象中的foo属性是否有任何好处:

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

VS

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

另外:

  • 如果foo["bar"]undefined
  • 会有什么结果
  • 如果foo undefined
  • 该怎么办?

1 个答案:

答案 0 :(得分: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');
}