in操作符的使用方式

129 阅读1分钟

in操作符的使用方式

有两种方式使用 in 操作符:单独使用和在 for-in 循环中使用。
    在单独使用时,in操作符会在通过对象能够访问给定属性时返回 true,无论该属性存在于实例中还是原型链中。
    for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性,包括继承的可枚举属性。
①单独使用in
function Person(){ 
} 
Person.prototype.name = "Nicholas"; 
Person.prototype.age = 29; 
Person.prototype.job = "Software Engineer"; 
Person.prototype.sayName = function(){ 
}; 
var person1 = new Person();
console.log('name' in person1)//true
②for-in循环中使用
var obj1 = {a:1, b:2, c:3};

for (var prop in obj1) {
  console.log(obj1[prop]);
}
// 1 2 3

应用场景

判断该属性存在于实例中还是存在于原型中
function hasPrototypeProperty(object,name){
    return  !object.hasOwnProperty(name) && (name in object);
}
console.log(hasPrototypeProperty(person1, "name"))//true
person1.name = 'zs'
console.log(hasPrototypeProperty(person1, "name"))//false