根据上述, 检测属性的时候会出现4种情况
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)); //trueconsole.log(person2.hasOwnPrototype(name)); //false
in操作符无论属性是存在实例本身中, 还是原型对象中, 就会返回true(情况2/情况3/情况4); 否则, 返回false(情况1).
console.log('name' in person1); //trueconsole.log('name' in person2); //true
结合in操作符和hasOwnProperty()就可以自定义函数来检测原型中是否存在给定的属性.
function hasprototypeProperty(object, name) { return !object.hasOwnPrototype(name) && (name in object);}console.log(hasPrototypeProperty(person1, 'name'));//falseconsole.log(hasPrototypeProperty(person2, 'name'));//true
原型中存在给定属性, 返回true(情况3). 否则返回false(情况1/情况2/情况4).
新闻热点
疑难解答