对象的成员检测

65 阅读1分钟
  •  instanceof:判断该左侧对象是否为右侧对象的实例化对象,或者说左侧对象能否在原型链上层层上查找到右侧函数的原型对象。(右侧是不是左侧的爸爸、爷爷、祖宗)
 function Parent() {}
  function Child() {}
  var child = new Child()
  console.log(child instanceof Parent); //false 
  console.log(child instanceof Child); //true  

image.png

  • isPrototypeOf 判断当前对象是否为另一个对象的原型,是为true,否为false
  function Parent() {}
  function Child() {}
  Child.prototype = new Parent()
  var c1 = new Child()
  console.log(Parent.prototype.isPrototypeOf(c1)); //true
  console.log(Child.prototype.isPrototypeOf(c1)); //true
  console.log(Child.isPrototypeOf(c1)); //Child与c1的原型对象相同,Child不是c1的原型对象

image.png

  •  hasOwnProperty() 判断对象是否有某个特定的属性,(注意说的是对象的属性,而不是对象原型的属性)必须用字符串指定该属性。
 function Parent() {
    this.life = 1
  }
  function Child() {
    this.name = "karen"
  }
  Child.prototype = new Parent()
  var c1 = new Child()
  console.log(c1.hasOwnProperty("name"))
  console.log(c1.hasOwnProperty("life"))

image.png

  • propertyIsEnumerable():判断给定的属性是否可以用 for...in 语句进行枚举。由于 for ... in 枚举是包含原型链上的属性的,但propertyIsEnumerable作用于原型方法上时,始终是返回false的,你可以这么认为,for...in可以枚举对象本身的属性和原型上的属性,而propertyIsEnumerable只能判断本身的属性是否可以枚举。此外,预定义的属性不是可列举的,而用户定义的属性总是可列举的。所以如果你只想遍历对象本身的属性,可以:
for (var key in obj) {
if (obj.propertyIsEnumerable(key) {console.log(key)}
}