javascript中的hasOwnProperty和isPrototypeOf
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前端開發(fā)"); var matou2=new siteAdmin("愚人碼頭","WEB前端開發(fā)"); 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
作者:Tyler Ning
出處:http://www.rzrgm.cn/tylerdonet/
本文版權歸作者和博客園共有,歡迎轉載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,如有問題,請微信聯(lián)系冬天里的一把火
浙公網(wǎng)安備 33010602011771號