1

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

hasOwnProperty使用点语法检查对象bar内部的属性有什么好处foo

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

对比

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

还:

  • 如果foo["bar"]是的话会发生什么undefined
  • 如果foo undefined
4

1 回答 1

13

看这个例子,

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');
}

于 2015-12-07T08:11:34.410 回答