本文小编为大家详细介绍“js中的hasOwnProperty()方法怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“js中的hasOwnProperty()方法怎么使用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
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
例子:
function Site(){
this.name = "CodePlayer";
this.url = "http://www.365mini.com/";
this.sayHello = function(){
document.writeln("欢迎来到" + this.name);
};
}
var obj = {
engine: "PHP"
,sayHi: function(){
document.writeln("欢迎访问" + this.url);
}
};
// 使用对象obj覆盖Site本身的prototype属性
Site.prototype = obj;
var s = new Site();
document.writeln( s.hasOwnProperty("name") ); // true
document.writeln( s.hasOwnProperty("sayHello") ); // true
// 以下属性继承自原型链,因此为false
document.writeln( s.hasOwnProperty("engine") ); // false
document.writeln( s.hasOwnProperty("sayHi") ); // false
document.writeln( s.hasOwnProperty("toString") ); // false
// 想要查看对象(包括原型链)是否具备指定的属性,可以使用in操作符
document.writeln( "engine" in s ); // true
document.writeln( "sayHi" in s ); // true
document.writeln( "toString" in s ); // true
读到这里,这篇“js中的hasOwnProperty()方法怎么使用”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/a791226606/article/details/110679991