JavaScript检测实例属性, 原型属性

0.前提

  • JavaScript对象的属性分为两种存在形态. 一种是存在实例中, 另一是存在原型对象中.
  • 根据上述, 检测属性的时候会出现4种情况
    1. 既不存在实例中, 也不存在原型对象中
    2. 存在实例中, 不存在原型对象中
    3. 不存在实例中, 存在原型对象中
    4. 既存在实例中, 也存在原型对象中

1.hasOwnPrototype()

hasOwnPrototype()接受一个字符串格式的属性名称, 如果实例本身存在该属性(情况2/情况4), 返回true. 否则, 返回false(情况1/情况3).

functino Person() {}
Person.prototype.name = 'apple';

var person1 = new Person();
var person2 = new Person();

person1.name = 'banana';

console.log(person1.hasOwnPrototype(name));  //true
console.log(person2.hasOwnPrototype(name));  //false

2.in操作符

in操作符无论属性是存在实例本身中, 还是原型对象中, 就会返回true(情况2/情况3/情况4); 否则, 返回false(情况1).

console.log('name' in person1);  //true
console.log('name' in person2);  //true

3.检测存在原型的属性

结合in操作符和hasOwnProperty()就可以自定义函数来检测原型中是否存在给定的属性.


function hasPrototypeProperty(object, name) {
     return !object.hasOwnPrototype(name) && (name in object);
}

console.log(hasPrototypeProperty(person1, 'name')); //false
console.log(hasPrototypeProperty(person2, 'name')); //true

原型中存在给定属性, 返回true(情况3). 否则返回false(情况1/情况2/情况4).

原文地址:https://www.cnblogs.com/refe/p/5175405.html