js中hasOwnProperty()方法详解

 更新时间:2023年04月21日 10:16:56   作者:Miss_Mr_Rui  
本文主要介绍了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()方法详解的文章就介绍到这了,更多相关js hasOwnProperty()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论