【发布时间】:2014-12-15 04:03:16
【问题描述】:
我在 Google 上搜索了很多,但找不到我要找的地方:
Benefit of using Object.hasOwnProperty vs testing if Property is undefined
How to determine if Native JavaScript Object has a Property/Method?
.. 和很多其他网站,但这不是我要找的地方。我真正的问题是:
为什么hasOwnProperty 在他的超类(原型)中找不到方法?为什么有人甚至使用hasOwnProperty?它比typeof 慢得多,如果您使用继承,它就不起作用。
..第二个问题:
在this 问题中,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());
}
【问题讨论】:
-
typeof和hasOwnProperty不相关。in运算符用于检查原型链中的属性,而hasOwnProperty仅直接检查该对象。如果您关心typeof/hasOwnProperty的性能,最快的方法可能是简单地使用评估值(因为undefined评估为false),例如if(test.alertMessage)
标签: javascript prototypal-inheritance