JavaScript hasOwnProperty() 函數詳解


hasOwnProperty()函數用於指示一個對象自身(不包括原型鏈)是否具有指定名稱的屬性。如果有,返回true,否則返回false

該方法屬於Object對象,由於所有的對象都"繼承"了Object的對象實例,因此幾乎所有的實例對象都可以使用該方法。

IE 5.5+、FireFox、Chrome、Safari、Opera等主流瀏覽器均支持該函數。

語法

object.hasOwnProperty( propertyName )

propertyName:string類型,指定參數的名稱。

返回值

hasOwnProperty()函數的返回值為Boolean類型。如果對象object具有名稱為propertyName的屬性,則返回true,否則返回false

此方法不會檢查對象的原型鏈中是否存在該屬性,該屬性只有是對象本身的一個成員才會返回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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM