欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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()內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論