本文介绍JavaScript中hasOwnProperty方法,用于检测对象是否拥有指定的自有属性。该方法不会查找原型链,返回布尔值。通过示例展示如何判断对象直接拥有的属性与继承属性的区别,帮助开发者准确进行属性检查。
JS中hasOwnProperty方法用法简介
hasOwnProperty用于判断对象是否包含自身的属性,该方法在查找时不会遍历原型链。
var obj = {
a: 1,
fn: function(){
},
c:{
d: 5
}
};
console.log(obj.hasOwnProperty('a')); // true
console.log(obj.hasOwnProperty('fn')); // true
console.log(obj.hasOwnProperty('c')); // true
console.log(obj.c.hasOwnProperty('d')); // true
console.log(obj.hasOwnProperty('d')); // false, obj对象没有d属性
var str = new String();
// split方法是String这个对象的方法,str对象本身是没有这个split这个属性的
console.log(str.hasOwnProperty('split')); // false
console.log(String.prototype.hasOwnProperty('split')); // truehasOwnProperty() 方法详解
hasOwnProperty(propertyName) 用于检测属性是否为对象的自有属性,若是则返回true,否则返回false;参数propertyName指要检测的属性名;
用法:object.hasOwnProperty(propertyName) // true/false
hasOwnProperty() 方法是 Object 的原型方法(也称实例方法),它定义在 Object.prototype 对象之上,所有 Object 的实例对象都会继承 hasOwnProperty() 方法。

hasOwnProperty() 只会检查对象的自有属性,对象原形上的属性其不会检测;但是对于原型对象本身来说,这些原型上的属性又是原型对象的自有属性,所以原形对象也可以使用hasOwnProperty()检测自己的自有属性;
let obj = {
name:'张睿',
age:18,
eat:{
eatname:'面条',
water:{
watername:'农夫山泉'
}
}
}
console.log(obj.hasOwnProperty('name')) //true
console.log(obj.hasOwnProperty('age')) //true
console.log(obj.hasOwnProperty('eat')) //true
console.log(obj.hasOwnProperty('eatname')) //false
console.log(obj.hasOwnProperty('water')) //false
console.log(obj.hasOwnProperty('watername')) //false
console.log(obj.eat.hasOwnProperty('eatname')) //true
console.log(obj.eat.hasOwnProperty('water')) //true
console.log(obj.eat.hasOwnProperty('watername')) //false
console.log(obj.eat.water.hasOwnProperty('watername')) //true到此这篇关于JS中hasOwnProperty方法用法简介的文章就介绍到这了,更多相关js hasOwnProperty用法内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!