javascript中的hasOwnProperty和isPrototypeOf

來源:互聯網
上載者:User

標籤:

hasOwnProperty:是用來判斷一個對象是否有你給出名稱的屬性或對象。不過需要注意的是,此方法無法檢查該對象的原型鏈中是否具有該屬性,該屬性必須是對象本身的一個成員。
isPrototypeOf是用來判斷要檢查其原型鏈的對象是否存在於指定對象執行個體中,是則返回true,否則返回false。

function siteAdmin(nickName,siteName){            this.nickName=nickName;            this.siteName=siteName;        }        siteAdmin.prototype.showAdmin = function() {            alert(this.nickName+"是"+this.siteName+"的站長!")        };        siteAdmin.prototype.showSite = function(siteUrl) {            this.siteUrl=siteUrl;            return this.siteName+"的地址是"+this.siteUrl;        };        var matou=new siteAdmin("愚人碼頭","WEB前端開發");        var matou2=new siteAdmin("愚人碼頭","WEB前端開發");        matou.age="30";//      matou.showAdmin();//      alert(matou.showSite("http://www.css88.com/"));        alert(matou.hasOwnProperty("nickName"));//true        alert(matou.hasOwnProperty("age"));//true        alert(matou.hasOwnProperty("showAdmin"));//false        alert(matou.hasOwnProperty("siteUrl"));//false        alert(siteAdmin.prototype.hasOwnProperty("showAdmin"));//true        alert(siteAdmin.prototype.hasOwnProperty("siteUrl"));//false        alert(siteAdmin.prototype.isPrototypeOf(matou))//true        alert(siteAdmin.prototype.isPrototypeOf(matou2))//true

 

1 for in可以擷取object的所有屬性,包括自訂屬性以及原型鏈屬性。

for(var attr in object){

  console.log(attr+":"object[attr]);

}

2 hasOwnProperty()只能擷取自訂屬性,無法擷取原型鏈屬性。

“str”.hasOwnProperty("split");//false

String.property.hasOwnProperty("split");//true

javascript中的hasOwnProperty和isPrototypeOf

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.