使用 Object.hasOwnProperty 与测试属性(如果属性未定义)的好处
Benefit of using Object.hasOwnProperty vs. testing if a property is undefined
由于hasOwnProperty有一些警告和怪癖(窗口/在Internet Explorer 8问题中广泛使用等(:
甚至有什么理由使用它吗?如果简单地测试一个属性是否未定义,它是否更合理且更简单?
例如:
var obj = { a : 'here' };
if (obj.hasOwnProperty('a')) { /* do something */ }
if (obj.a !== undefined) { /* do something */ }
// Or maybe (typeof (obj.a) !== 'undefined')
我更喜欢使用跨浏览器友好和最新的方法。
我也看到这个原型被覆盖为 hasOwnProperty,它可以工作,但我不相信它的有用性......
if (!Object.prototype.hasOwnProperty) {
Object.prototype.hasOwnProperty = function(prop) {
var proto = this.__proto__ || this.constructor.prototype;
return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]);
};
}
hasOwnProperty 不检查未定义的值。它只检查是否将属性分配给对象,即使未定义:
var obj = { a : undefined };
obj.hasOwnProperty("a") // true
obj.a === undefined // true
obj.hasOwnProperty("b") // false
obj.b === undefined // true
方法检查属性是否直接分配给对象。
因此,如果属性"a"在原型中,hasOwnProperty 将过滤它。
function NewClass() {}
NewClass.prototype = { a: 'there' };
var obj = new NewClass();
if (obj.hasOwnProperty('a')) { /* Code does not work */ }
if (obj.a !== undefined) { /* Code works */ }
因此,在许多情况下,hasOwnProperty更安全。
作为Pavel Gruba给出的答案以及您提供的polyfil的进一步信息:
据我所知,对于本机不支持它的浏览器,没有好的方法可以 polyfil hasOwnProperty
。我在野外见过很多不同的,它们都会产生假阳性或假阴性。如果我绝对别无选择,那么这就是我为我使用而创建的,但它也遭受误报和误报。根据MSDN。
在以下文档模式下受支持:怪癖、Internet Explorer 6标准, Internet Explorer 7 标准, Internet Explorer 8标准, Internet Explorer 9 标准, Internet Explorer 10标准。在 Windows 应用商店应用中也受支持。
JavaScript
function is(x, y) {
if (x === y) {
if (x === 0) {
return 1 / x === 1 / y;
}
return true;
}
var x1 = x,
y1 = y;
return x !== x1 && y !== y1;
}
function hasOwnProperty(object, property) {
var prototype;
return property in object && (!(property in (prototype = object.__proto__ || object.constructor.prototype)) || !is(object[property], prototype[property]));
}
function NewClass() {}
NewClass.prototype = {
a: 'there'
};
var obj = new NewClass();
if (obj.hasOwnProperty("a")) {
console.log("has property")
}
if (hasOwnProperty(obj, "a")) {
console.log("has property")
}
在JSFiddle上。
相关文章:
- 主干中的模型属性未定义
- JavaScript 2d 数组导致“无法读取未定义的属性'未定义'”
- JSON对象属性未定义
- Waypoint的循环,退出循环后属性未定义
- Javascript:错误“无法设置属性”..'未定义”
- 翡翠 - 显示对象属性 - 未定义
- 属性未定义,但控制台.log可以看到它
- JavaScript 对象的属性未定义
- Javascript 对象属性未定义(但属性已设置)
- DOM 元素属性未定义 - jquery / ruby on rails.
- Nodejs JSON 属性未定义
- 错误:窗口打开器的属性未定义
- angular Js:Array.lenght属性未定义
- 正在尝试访问JavaScript对象的属性=未定义
- Marionette属性未定义,请从API获取
- AngularJS作用域属性未定义
- 对象的属性未定义,尽管已指定值
- 为什么我一直收到一个错误,说对象属性未定义
- 对象属性未定义,但我看到它不是
- .map()img src属性未定义