我在谷歌上搜索了很多,但找不到我要找的地方:
如果属性未定义,使用Object.hasOwnProperty与测试的好处
杰斯普夫速度试验
。。和很多其他网站,但这不是我要找的地方。我真正的问题是:
为什么hasOwnProperty 没有在他的超类(原型)中找到一个方法?为什么有人会使用hasOwnProperty**?它比** typeof 慢得多,如果您正在处理继承问题,它将无法工作。
。。第二个问题:
在“这问题”中,Barney回答说,您必须使用if ('property' in objectVar)来检查属性是否存在,但没有解释原因。有人知道你为什么要用这个结构吗?
var objA = function(){};
objA.prototype.alertMessage = function(){
return 'Hello A';
};
var objB = function(){
this.hello = function(){
return 'hello';
};
};
// Inheritance
objB.prototype = Object.create(objA.prototype);
objB.prototype.constructor = objA;
var test = new objB();
if (test.hasOwnProperty("alertMessage")){
console.log("hasOwnProperty: " + test.alertMessage());
}
if (typeof test.alertMessage === "function"){
console.log("typeof: " + test.alertMessage());
}
if (test.hasOwnProperty("hello")){
console.log("hasOwnProperty: " + test.hello());
}
if (typeof test.hello === "function"){
console.log("typeof: " + test.hello());
}查看jsFiddle
发布于 2014-10-20 08:24:53
使用(在某些情况下必须使用) hasOwnProperty的原因有很多,以及它的行为是什么:
hasOwnProperty检查您测试的对象是否拥有具有给定名称的属性。如果它从另一个对象(它的原型)继承了一个方法/属性,那么该属性的所有者不是对象,而是它的原型。因此,对象没有自己的属性,称为Xtypeof大部分时间都能工作,但是对象可以如下所示:var o = {foo: undefined}。当然,在typeof上使用o.foo会产生"undefined",但是对象确实拥有一个名为foo的属性if ('properyname' in object)是一种解决办法,它结合了这两个方面的优点:在o = {foo: undefined};的情况下,它将计算为真,而不需要查找hasOwnPropery方法(这是Object.prototype的一个属性),或者使用上下文绑定的函数调用等等。它还将在原型链中找到属性。因此,请考虑以下例子:
var o = {foo: undefined,
toString: undefined};//overwrite inherited method
console.log(typeof o.foo);//undefined
console.log(typeof o.toString);//undefined
console.log(o.hasOwnProperty('toString'));//true
delete(o.toString);
console.log(typeof o.toString);//function
if ('valueOf' in o)
console.log(o.valueOf === Object.prototype.valueOf);//true
if ('foo' in o)
console.log(o.foo);//undefined另一件重要的事情需要注意的是,关于hasOwnProperty在处理继承时不起作用的说法是完全错误的。您在JS中使用的每个对象都至少继承了一个原型。认识、理解和尊重这一点是很重要的。如果您循环一个对象,建议确保您实际上是在迭代属于对象本身的属性。因此,这种情况并不少见:
for (p in obj)
{
if (obj.hasOwnProperty(p))
//process property
}这是为了避免对原型链中的所有属性进行迭代的代码,这可能会破坏超级对象。
if (!Object.prototype.hasProperty)
{//dirty check ;-P
Object.prototype.hasProperty = (function(OP)
{
return function(name)
{
//typeof for speed: if value is not undefined, return true
if (typeof this[name] !== 'undefined' || this.hasOwnProperty(name))
return true;
if (this === OP)//we've just checked the Object.prototype, found nothing, so return false
return false;
return Object.getPrototypeOf(this).hasProperty(name);//check prototype
};
}(Object.prototype));//OP is object prototype
}https://stackoverflow.com/questions/26461135
复制相似问题