对象的成员访问检测

对象的成员访问检测

  • istanceof:检测对象是不是某个对象的实例化 注意:在某个原型链上也算

  • isPrototypeOf():在调试的时候用 检测对象的的Prototype是否

     function Parent() {
         // pass
     }
    function Child() {
        // pass
    }
    // 利用原型链的思想来模拟继承的关系 Child此时既是Parent的实例化,又是Child的实例化
    Child.prototype = new Parent()
    var cd = new Child()
    // 运算符instanceof 检测对象是不是某个对象的实例化
    console.log(cd instanceof Parent) // true
    console.log(cd instanceof Child) // true
    // isPrototypeOf() 在调试的时候用 检测对象的的Prototype布尔值
    console.log(Child.prototype.isPrototypeOf(cd)) // true
    console.log(Parent.prototype.isPrototypeOf(cd)) // true
    
  • hasOwnProperty():判断对象是否有某个特定的属性(说的是对象的属性,不是对象原型的属性),必须用字符串指定该属性

    function Parent() {
        this.index = 1
    }
    function Child() {
        this.name = 'lili'
    }
    // 利用原型链的思想来模拟继承的关系 Child此时既是Parent的实例化,又是Child的实例化
    Child.prototype = new Parent()
    var Child = new Child()
    console.log(Child.hasOwnProperty('name'))	// true
    console.log(Child.hasOwnProperty('index'))	//false
    
  • propertyIsEnumerable():判断给定的属性是否可以用for...in语句进行枚举。for...in枚举是包含原型链上所有的属性,但propertyIsEnumerable()作用于原型方法时,始终返回false。可以简单认为for..in枚举对象本身的属性和原型链上的属性,而propertyIsEnumerable()只能判断本身是否可以被枚举。注意:预定义的属性不可枚举,而用户定义的属性总是可枚举的。伪数组不能被propertyIsEnumerable枚举

举例:利用对象来判断类型

var re = Object.prototype.toString.call(20)
console.log(re)
posted @ 2022-06-12 13:51  a立方  阅读(22)  评论(0编辑  收藏  举报