js属性对象的hasOwnProperty方法

本文深入探讨了JavaScript中对象的自生属性与继承属性的区别,通过实例演示了如何使用hasOwnProperty方法判断属性的存在性,以及如何遍历一个对象的所有自身属性。

判断自生属性与继承性

 function foo() {
            this.name = 'foo'
            this.sayHi = function () {
                console.log('Say Hi')
            }
        }

        foo.prototype.sayGoodBy = function () {
            console.log('Say Good By')
        }

        var myPro = new foo()

        console.log(myPro.name) // foo
        console.log(myPro.hasOwnProperty('name')) // true
        console.log(myPro.hasOwnProperty('toString')) // false
        console.log(myPro.hasOwnProperty('hasOwnProperty')) // fasle
        console.log(myPro.hasOwnProperty('sayHi')) // true
        console.log(myPro.hasOwnProperty('sayGoodBy')) // false
        console.log('sayGoodBy' in myPro) // true

判断自生属性是否存在

var o = new Object();
o.prop = 'exists';
function changeO() {
    o.newprop = o.prop;
    delete o.prop;
}
console.log(o.hasOwnProperty('prop'));  // true
changeO();
console.log(o.hasOwnProperty('prop'));  // false

遍历一个对象的所有自身属性
在看开源项目的过程中,经常会看到类似如下的源码。for…in循环对象的所有枚举属性,然后再使用hasOwnProperty()方法来忽略继承属性。

var buz = {
    fog: 'stack'
};

for (var name in buz) {
    if (buz.hasOwnProperty(name)) {
        alert("this is fog (" + name + ") for sure. Value: " + buz[name]);
    }
    else {
        alert(name); // toString or something else
    }
}
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李学软件

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值