js检测属性是否在原型上
在单独使用时,in操作符会在可以通过对象访问指定属性时返回true,无论该属性是在实例上还是原型上。
hasOwnProperty()方法继承自Object,会在属性存在于调用他的对象实例上时返回true
基于上述特征我们可以设计一个函数用来检测某个属性是否存在于原型上
function hasPrototypeProperty(object, name) { return !object.hasOwnProperty(name) && (name in object); }
测试下
function Person() { }; Person.prototype.name = 'hututu';//给原型上添加属性 let person1 = new Person(); console.log(hasPrototypeProperty(person1, 'name'));
![image-20220723110938404](https://uploadfiles.nowcoder.com/files/20220723/904032161_1658545917175/2863962-20220723110939133-827973803.png)