Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
也可以判断当前Object中是否有某个key。
判断自身属性是否存在
var o = new Object();
o.prop = 'exists';
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); // true
changeO();
o.hasOwnProperty('prop'); // false
判断自身属性与继承属性
function foo() {
this.name = 'foo'
this.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
https://www.cnblogs.com/weiqinl/p/8683207.html