本文详解JavaScript中hasOwnProperty()方法的用法。该方法用于检测属性是否为对象的自有属性,忽略原型链上的属性。通过实例对比in操作符,说明如何准确判断对象自身拥有的属性,避免原型属性带来的误判。
hasOwnProperty() 方法定义与语法
hasOwnProperty(propertyName) 方法用于检测指定属性是否为对象的自有属性。若属性存在于对象自身,则返回 true;否则返回 false。参数 propertyName 表示需要检测的属性名称。
调用语法为 object.hasOwnProperty(propertyName),返回值类型为布尔值 true 或 false。
hasOwnProperty() 是 Object 的原型方法,定义在 Object.prototype 上。所有 Object 实例对象均继承此方法。

该方法仅检查对象的自有属性,不检测原型链上的属性。但对于原型对象本身,其原型属性即为其自有属性,因此原型对象也可使用 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关于 JavaScript 中 hasOwnProperty() 方法的介绍至此结束。如需了解更多相关内容,可搜索本站往期文章或浏览后续文章。感谢支持。