js原型与in操作符

有两种方式使用in操作符:单独使用和在for-in循环中使用。在单独使用时,in操作符会在通过对象能够访问给定属性时返回true,无论该属性存在实例中还是原型中。

function Person(){
  
}

Person.prototype.name = "Tom";
Person.prototype.age = 18;
Person.prototype.sayName = function(){
  console.log(this.name);
}

var person1 = new Person();

console.log(person1.name);  //"Tom",来自原型
console.log(person1.hasOwnProperty("name"));  //false
console.log("name" in person1);  //true

person1.name = "Grey";
console.log(person1.name);  //"Grey",来自实例
console.log(person1.hasOwnProperty("name"));  //true
console.log("name" in person1);  //true
  • 从上面的例子可以看出,name属性要么直接在原型上访问到,要么直接在实例上访问到。
  • 调用"name" in person1始终都返回true
  • 当属性存在于实例中时,调用hasOwnProperty()返回true,存在于原型中时返回false。
  • 同时使用hasOwnProperty()和in操作符就可以知道属性是存在于原型中还是实例中了,如下所示:
function hasPrototypeProperty(object,name){
  return !object.hasOwnProperty(name) && (name in object);
}

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

unction Person(){
  
}

Person.prototype.name = "Tom";
Person.prototype.age = 18;
Person.prototype.sayName = function(){
  console.log(this.name);
}

var person = new Person();
console.log(hasPrototypeProperty(person,"name"))

person.name = "Grey";
console.log(hasPrototypeProperty(person,"name")) //true

function hasPrototypeProperty(object,name){
  return !object.hasOwnProperty(name) && (name in object);  //false
}

在使用for-in循环时,返回的时所有能够通过对象访问的、可枚举夫人属性,其中既包括存在于实例中的属性,也包括存在于原型中的属性。要取的对象上所有的可枚举的实例属性,可以使用Object.keys()方法。这个方法要接收一个对象作为参数,返回一个包含所有可枚举属性的字符串数组。

function Person(){
  
}

Person.prototype.name = "Tom";
Person.prototype.age = 18;
Person.prototype.sayName = function(){
  console.log(this.name);
}

var keys = Object.keys(Person.prototype);
console.log(keys);  ["name", "age", "sayName"]

var person = new Person();
person.name = "Grey";
person.age = 20;
var keys1 = Object.keys(person);
console.log(keys1);  ["name", "age", "sayName"]

如果你想得到所有属性,无论它是否可枚举,都可以使用Object.getOwnPropertyNames()方法。

function Person(){
  
}

Person.prototype.name = "Tom";
Person.prototype.age = 18;
Person.prototype.sayName = function(){
  console.log(this.name);
}

var keys = Object.getOwnPropertyNames(Person.prototype);
console.log(keys);  //["constructor", "name", "age", "sayName"]

注意结果中包含了不可枚举的属性constructor属性。Object.keys()和Object.getOwnPropertyNames()方法都可以用来代替for-in循环。

你可能感兴趣的:(js原型与in操作符)