hasOwnProperty與in的區別


1、hasOwnProperty只能判斷是否是屬於自身的屬性,無法找到原型身上的屬性(hasOwnProperty()只在屬性存在於實例中時才返回true

 

Person.prototype.lastName = "Deng";

function Person() {
}

var person = new Person();
person.age = 12;

if (person.hasOwnProperty('lastName')) {
    //找不到不執行
    console.log(person.lastName)
}

if (person.hasOwnProperty('age')) {
    //能找到會輸出12
    console.log(person.age)
}

 

2、in原型身上的屬性也能找到(in操作符只要通過對象能訪問到屬性就返回true

console.log('lastName'in person)
//返回true

 


免責聲明!

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



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