1、hasOwnProperty():用来检测一个属性是否是对象的自有属性,而不是从原型链继承的。如果该属性是自有属性,那么返回 true,否则返回 false。
function F(){
this.name="自有属性"
}
F.prototype.name1="继承属性"
var f = new F()
console.log(f.hasOwnProperty("name"))//true
console.log(f.hasOwnProperty("name1"))//false
2、凡是构造函数的原型属性(原型对象包含的属性),都是继承属性,使用 hasOwnProperty() 方法检测时,都会返回 false。但是,对于原型对象本身来说,这些原型属性又是原型对象的自有属性,所以返回值又是 true。
function foo() {
this.name = 'foo'
this.sayHi = function () {
console.log('Say Hi')
}
}
foo.prototype.sayGoodBy = function () {
console.log('Say Good By')
}
var myPro = new foo()
var mypro1 = foo.prototype
console.log(myPro.hasOwnProperty('name')) //true
console.log(mypro1.hasOwnProperty('sayGoodBy')) //true
console.log(mypro1.hasOwnProperty('name')) //false
console.log(myPro.hasOwnProperty('sayGoodBy')) //false
3、hasOwnProperty 作为属性名(JavaScript 并没有保护 hasOwnProperty 属性名,因此,可能存在于一个包含此属性名的对象,有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果)
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
console.log(foo.hasOwnProperty('bar')); //false
// 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法
// 使用另一个对象的`hasOwnProperty` 并且call
console.log(({}).hasOwnProperty.call(foo, 'bar')); //true
// 也可以使用 Object 原型上的 hasOwnProperty 属性
console.log(Object.prototype.hasOwnProperty.call(foo, 'bar')); //true