溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

js中的hasOwnProperty()方法怎么使用

發(fā)布時(shí)間:2023-04-21 16:25:15 來源:億速云 閱讀:84 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“js中的hasOwnProperty()方法怎么使用”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“js中的hasOwnProperty()方法怎么使用”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

hasOwnProperty(propertyName)方法 是用來檢測(cè)屬性是否為對(duì)象的自有屬性,如果是,返回true,否者false; 參數(shù)propertyName指要檢測(cè)的屬性名;

用法:object.hasOwnProperty(propertyName) // true/false

hasOwnProperty() 方法是 Object 的原型方法(也稱實(shí)例方法),它定義在 Object.prototype 對(duì)象之上,所有 Object 的實(shí)例對(duì)象都會(huì)繼承 hasOwnProperty() 方法。

js中的hasOwnProperty()方法怎么使用

hasOwnProperty() 只會(huì)檢查對(duì)象的自有屬性,對(duì)象原形上的屬性其不會(huì)檢測(cè);但是對(duì)于原型對(duì)象本身來說,這些原型上的屬性又是原型對(duì)象的自有屬性,所以原形對(duì)象也可以使用hasOwnProperty()檢測(cè)自己的自有屬性;

let obj = {
    name:'張睿',
    age:18,
    eat:{
        eatname:'面條',
        water:{
            watername:'農(nóng)夫山泉'
        }
    }
}
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);
    }
};
// 使用對(duì)象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

// 想要查看對(duì)象(包括原型鏈)是否具備指定的屬性,可以使用in操作符
document.writeln( "engine" in s ); // true
document.writeln( "sayHi" in s ); // true
document.writeln( "toString" in s ); // true

讀到這里,這篇“js中的hasOwnProperty()方法怎么使用”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI