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