JS中hasOwnProperty方法用法简介
作者:前端不加班
hasOwnProperty(propertyName)方法 是用来检测属性是否为对象的自有属性,如果是,返回true,否者false; 参数propertyName指要检测的属性名,这篇文章给大家介绍JS中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用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
