2.原型与in操作符



// in有两种用法,一种是使用在for-in循环中,一种是单独使用。单独使用时,in操作符会在对象可以访问给定属性时返回true



function Person(){

}
Person.prototype.name="summer";
Person.prototype.age=20;
Person.prototype.job="enginner";
Person.prototype.sayName=function(){
console.log(this.name);
}
var person1=new Person();
var person2=new Person();
console.log(person1.hasOwnProperty("name")); // false
console.log("name" in person1); // true

person1.name="summer2";
console.log(person1.name); // summer2---来自实例
console.log(person1.hasOwnProperty("name")); // true
console.log("name" in person1); // true

console.log(person2.name); // summer---来自原型
console.log(person2.hasOwnProperty("name")); // false
console.log("name" in person2); // true

// in操作符只要通过对象能访问到属性就返回true,hasOwnProperty只在属性存在于实例中时才返回true,
// 因此只要in操作符返回true,hasOwnProperty返回false时可以确定该属性是原型中的属性

function hasPrototypePropty(object,name){
return !object.hasOwnProperty(name)&&(name in object);
}

function Person(){

}
Person.prototype.name="summer";
Person.prototype.age=20;
Person.prototype.job="enginner";
Person.prototype.sayName=function(){
console.log(this.name);
}

var person= new Person();
alert(hasPrototypePropty(person,"name")); // true
person.name="su";
alert(hasPrototypePropty(person,"name")); // false



原文地址:https://www.cnblogs.com/liululu/p/5820646.html