hasOwnProperty(propertyName)
该方法用于检查既定的属性在对象实例中是否存在,作为参数的属性名必须是字符串类型。
如:
let obj = {
a: 'a1',
b: 'b2'
}
Object.prototype.c = "c3";
console.log(obj.hasOwnProperty("a")) // true
console.log(obj.hasOwnProperty("b")) // true
console.log(obj.hasOwnProperty("c")) // false
上面的例子中,因为对象obj中有a属性和b属性,所以返回true;因为没有c属性,所以返回false。
in操作符,同样也是检测既定的属性是否存在于对象中,但是不一样的是,只要对象能访问到的属性,in操作符都会返回true,即使在原型上存在该属性。
如:
let obj = {
a: 'a1',
b: 'b2'
}
Object.prototype.c = "c3";
console.log("a" in obj) // true
console.log("b" in obj) // true
console.log("c" in obj) // true