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