360免费做网站电话,网页素材制作,app设计原理,企业门户网站建设jspIE 5.5、FireFox、Chrome、Safari、Opera等主流浏览器均支持该函数。 Object的hasOwnProperty()方法返回一个布尔值#xff0c;判断对象是否包含特定的自身#xff08;非继承#xff09;属性。可以用于区分自身属性和继承属性#xff0c;如下
function foo() {this.name …IE 5.5、FireFox、Chrome、Safari、Opera等主流浏览器均支持该函数。 Object的hasOwnProperty()方法返回一个布尔值判断对象是否包含特定的自身非继承属性。可以用于区分自身属性和继承属性如下
function foo() {this.name foothis.sayHi function () {console.log(Say Hi)}
}foo.prototype.sayGoodBy function () {console.log(Say Good By)
}
let myPro new foo()
console.log(myPro.name) // foo
console.log(myPro.hasOwnProperty(name)) // true
console.log(myPro.hasOwnProperty(toString)) // false
console.log(myPro.hasOwnProperty(hasOwnProperty)) // fasle
console.log(myPro.hasOwnProperty(sayHi)) // true
console.log(myPro.hasOwnProperty(sayGoodBy)) // false
console.log(sayGoodBy in myPro) // true 还可以用于遍历一个对象的所有自身属性
在看开源项目的过程中经常会看到类似如下的源码。for...in循环对象的所有枚举属性然后再使用hasOwnProperty()方法来忽略继承属性。
var buz {fog: stack
};
for (var name in buz) {if (buz.hasOwnProperty(name)) {alert(this is fog ( name ) for sure. Value: buz[name]);}else {alert(name); // toString or something else}
} 当对象有属性名 hasOwnProperty 冲突时 JavaScript 并没有保护 hasOwnProperty 属性名因此可能存在于一个包含此属性名的对象有必要使用一个可扩展的hasOwnProperty方法来获取正确的结果
var foo {hasOwnProperty: function() {return false;},bar: Here be dragons
};
foo.hasOwnProperty(bar); // 始终返回 false
// 如果担心这种情况可以直接使用原型链上真正的 hasOwnProperty 方法
// 使用另一个对象的hasOwnProperty 并且call
({}).hasOwnProperty.call(foo, bar); // true
// 也可以使用 Object 原型上的 hasOwnProperty 属性
Object.prototype.hasOwnProperty.call(foo, bar); // true
解决办法如上通过call方法调用原型链上的hasOwnProperty方法 学习网址http://www.cnblogs.com/weiqinl/p/8683207.html