hasOwnProperty && in
in 的用法
用来检查对象中是否存在某个属性(不区分实例属性和原型链属性)
function Person(name) {
this.name = name
}
Person.prototype.age = 18
Person.prototype.sayHi = function () {
console.log('hello world');
}
let p1 = new Person()
console.log('name' in p1) // true
console.log('age' in p1) // true
console.log('sayHi' in p1) // true
复制代码
hasOwnProperty
function Animal(dog) {
this.name = name
}
Animal.prototype.species = '陆地'
Animal.prototype.run = function() {
console.log('跑的挺快');
}
let a1 = new Animal()
console.log(a1.hasOwnProperty('name')) // true
console.log(a1.hasOwnProperty('species')) // false
console.log(a1.hasOwnProperty('run')) // false
复制代码
总结:
in 运算符: 检查对象中是否存在某个属性(不区分实例属性和原型链属性);
hasOwnProperty 运算符:检查对象中是否存在某个属性(只检查实例属性);
扩展:
- 判断原型链中是否存在某个属性的方法:
function isProperty(obj, property) {
return !obj.hasOwnProperty(property) && (property in obj)
}
复制代码
- Object.create(null) 创建的对象,hasOwnProperty() 检测不到
let ownObj = Object.create(null)
ownObj.name = 'ml'
console.log(ownObj);
console.log('name' in ownObj); // true
// console.log(ownObj.hasOwnProperty('name')); // false
console.log(Object.prototype.hasOwnProperty.call(ownObj, 'name')); // true
复制代码
对象没有连接到 Object.prototype 上