1.in判断属性是否在对象属性和原型属性上面
<script>
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.height="120";
console.log("name" in Person);
console.log("height" in Person);
var p=new Person();
console.log("name" in p);
console.log("name" in Person)
效果:
2.hasOwnproperty判断属性是否在实例属性里面
<script>
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.height="120";
var p=new Person();
console.log(p.hasOwnProperty("name"));
console.log(p.hasOwnProperty("height"));
</script>
上面一个in判断是实例属性或者原型属性,hasOwnProperty方法是判断是否在实例属性中,那怎么判断只在原型属性里面呢,动动脑子一想,不就可以想出并,交等方法吗console.log("height" in p&&!p.hasOwnProperty("height"));
好的这个问题解决了,让我们再好好来理解一个方法isPrototypeof,就是判断是否是一个原型对象构造出来的对象。
console.log(Person.prototype.isPrototypeOf(p));