通过hasOwnProperty()这个方法,hasOwnProperty()检测一个属性是否属于自身对象,还是继承于原型链上的;属于自身对象,返回true,否则返回false。
function Person(name,age){
this.name=name;
this.age=age;
}
Person.prototype.sex="男";
const p=new Person("张三",18);
p.phone=123456;
p.height=188;
console.log(p);//Person { name: '张三', age: 18, phone: 123456, height: 188 }
console.log(p.hasOwnProperty("phone"));//true--->属于自身
console.log(p.hasOwnProperty("sex"));//false---->“sex”属于原型链上的
//结合for...in使用,只想for..in打印对象自身的,不打印整个原型链上的;
for (let key in p){
if(p.hasOwnProperty(key)){
console.log(key);//name age phone height
}
}