object.hasOwnProperty
hasOwnProperty()
方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性
语法
obj.hasOwnProperty(prop)
参数
返回值
用来判断某个对象是否含有指定的属性的Boolean
?。
描述
示例
使用hasOwnProperty
方法判断属性是否存在
下面的例子检测了对象o
是否含有自身属性prop:
o = new Object();
o.prop = 'exists';
function changeO() {
o.newprop = o.prop;
delete o.prop;
}
o.hasOwnProperty('prop'); // returns true
changeO();
o.hasOwnProperty('prop'); // returns false
自身属性与继承属性
下面的例子演示了hasOwnProperty
方法对待自身属性和继承属性的区别:
o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop'); // returns true
o.hasOwnProperty('toString'); // returns false
o.hasOwnProperty('hasOwnProperty'); // returns false
遍历一个对象的所有自身属性
下面的例子演示了如何在遍历一个对象的所有属性时忽略掉继承属性,注意这里for...in
? 循环只会遍历可枚举属性,所以不应该基于这个循环中没有不可枚举的属性而得出?hasOwnProperty 是严格限制于可枚举项目的(如同?
Object.getOwnPropertyNames()
)。
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.log('this is fog (' +
? name + ') for sure. Value: ' + buz[name]);
}
else {
console.log(name); // toString or something else
}
}
使用 hasOwnProperty
作为属性名
JavaScript 并没有保护 hasOwnProperty 属性名,因此某个对象是有可能存在使用这个属性名的属性,使用外部的?hasOwnProperty 获得正确的结果是需要的:
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
// Use another Object's hasOwnProperty
// and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true
// It's also possible to use the hasOwnProperty property
// from the Object prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
Note that in the last case there are no newly created objects.
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.5. |
ECMAScript 5.1 (ECMA-262)The definition of 'Object.prototype.hasOwnProperty' in that specification. | Standard | ? |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Object.prototype.hasOwnProperty' in that specification. | Standard | ? |
ECMAScript Latest Draft (ECMA-262)The definition of 'Object.prototype.hasOwnProperty' in that specification. | Living Standard | ? |
浏览器兼容性
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com