I've searched a lot on Google but couldn't found where I was looking for:
Benefit of using Object.hasOwnProperty vs testing if Property is undefined
How to determine if Native JavaScript Object has a Property/Method?
.. and a lot of other websites, but this is not where I am looking for. My real question is:
Why does hasOwnProperty
not find a method in his super class(prototype)? And why does somebody even use hasOwnProperty
? It's much slower than typeof
and it doesn't work if you are working with inheritance.
.. second question:
In this question Barney answers that you have to use if ('property' in objectVar)
to check if a property exists, but doesn't explain why. Does someone knows why you would use this structure?
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());
}