hasOwnProperty 基本概念
hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中(非继承属性)是否具有指定的属性,
如果 object 具有带指定名称的属性,则 hasOwnProperty 方法返回 true,否则返回 false。此方法不会检查对象原型链中的属性;该属性必须是对象本身的一个成员。
使用语法
obj.hasOwnProperty(prop)
* obj(必需),为实例的对象
* prop(必需),对象的属性名,  string形式
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
   | //实例化一个对象 const obj = new Object(); //为obj添加属性name obj.name = "陌寒"; //为obj添加属性sex obj.sex="male" //为obj添加family属性 obj.family = {     father:"陌上寒",     mather:"陌下寒" }
  const a = obj.hasOwnProperty('name'); console.log(a);// true const b = obj.hasOwnProperty('father'); console.log(b);//false const bb = obj.family.hasOwnProperty('father'); console.log(b);//true //删除obj的name属性 delete obj.name const c = obj.hasOwnProperty('name'); console.log(c); // false const d = obj.hasOwnProperty('sex'); console.log(d); //  true
   | 
 
无法通过obj.hasOwnProperty(prop)判断继承属性
1 2 3 4 5 6 7 8 9 10
   | obj= new Object(); obj.name = '陌上寒'; const a = obj.hasOwnProperty('name'); console.log(a);//true const b = obj.hasOwnProperty('toString'); console.log(b);//false const bb = obj.prototype.hasOwnProperty('toString'); console.log(b);//false const c = obj.hasOwnProperty('hasOwnProperty'); console.log(c);//false
   | 
 
如果要判断继承属性,通过原型链prototype判断
1 2 3 4
   | const d = Object.prototype.hasOwnProperty('toString') console.log(d);//true const e = String.prototype.hasOwnProperty('split') console.log(e);//true
  | 
 
遍历一个对象的所有自身属性
通过for…in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。
  换一种写法
1 2 3 4 5 6 7 8 9 10 11 12
   | const obj ={     name:"陌上寒",     sex:"male" } for (let key in obj) {     if (obj.hasOwnProperty(key)) {         console.log(`${key}: ${obj[key]}`)     }     else          console.log(key);      } }
  | 
 
输出:

注意:
JavaScript 并没有保护 hasOwnProperty 属性名,使用起来可能会有坑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | const foo = {     hasOwnProperty: function() {         return false;     },     bar: '这是一个坑,可能永远返回false' }; const hasBar = foo.hasOwnProperty('bar');  console.log(hasBar);// 始终返回 false
  // 如果担心这种情况,可以直接使用原型链上真正的 hasOwnProperty 方法 const a = ({}).hasOwnProperty.call(foo, 'bar'); // true console.log(a); // 也可以使用 Object 原型上的 hasOwnProperty 属性 const b = Object.prototype.hasOwnProperty.call(foo, 'bar'); // true console.log(b);
  |