JavaScript中的对象成员检测

1、instanceof:判断该对象是否为另一个对象的实例

案例1
 function Parent() {

        }

        function Child() {

        }
        var child = new Child()
        console.log(child instanceof Parent); //false
        console.log(child instanceof Child); //true

结果:在这里插入图片描述

案例2
function Parent() {

        }

        function Child() {

        }
        Child.prototype = new Parent()
        var child = new Child()
        console.log(child instanceof Parent); //true
        console.log(child instanceof Child); //true

结果:在这里插入图片描述

2、 isPrototypeOf:判断一个对象象是否为一个实例的原型

 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

结果:在这里插入图片描述

3、hasOwnProperty()

    hasOwnProperty:判断对象是否有某个特定的属性,
    (注意说的是对象的属性,而不是对象原型的属性)必须用字符串指定该属性。
   function Parent() {
            this.life = 1
        }

        function Child() {
            this.name = "karen"
        }
        Child.prototype = new Parent()
        var c1 = new Child()
        console.log(c1.hasOwnProperty("name")); //true
        console.log(c1.hasOwnProperty("life")); //false

结果:在这里插入图片描述

4、propertyIsEnumerable():判断给定的属性是否可以用 for…in 语句进行枚举。

//由于 for ... in 枚举是包含原型链上的属性的,
        //但propertyIsEnumerable作用于原型方法上时,始终是返回false的,
        //你可以这么认为,for...in可以枚举对象本身的属性和原型上的属性,
        //而propertyIsEnumerable只能判断本身的属性是否可以枚举。
        //此外,预定义的属性不是可列举的,而用户定义的属性总是可列举的。
        所以如果你只想遍历对象本身的属性,可以: 
         for (var key in obj) {
            if (obj.propertyIsEnumerable(key)) {
                 console.log(key)
             }
         }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值