I understand that the hasOwnProperty
method in JavaScript exists to identify properties only of the current type, but there is something in the prototype chain here that is confusing to me.
Let us imagine that I define a type called Bob, and assign two child functions to my Bob type in two different ways:
function Bob()
{
this.name="Bob";
this.sayGoodbye=function()
{
console.log("goodbye");
}
}
Bob.prototype.sayHello= function()
{
console.log("hello");
}
Now aside from having access to closure scope in the case of sayGoodbye
, it seems to me that both functions belonging to the Bob
class should be more or less equal. However, when I look for them with hasOwnProperty
they are not the same as far as JavaScript is concerned:
var myBob = new Bob();
console.log( myBob.name ); // Bob, obviously
console.log( myBob.hasOwnProperty("sayHello")); // false
console.log( myBob.hasOwnProperty("sayGoodbye")); // true
console.log( "sayHello" in myBob ); // true
What is happening here in terms of scope? I could not create an instance of the Bob
type without having the sayHello()
and sayGoodbye()
properties connected to it, so why is the prototype method a second class citizen as far as hasOwnProperty
is concerned? Is Bob.prototype
a type that exists somehow independently of the Bob
type, from which Bob
inherits everything?
hasOwnProperty
exists only to check the object itself for properties, it explicitly does not walk up the prototype chain, as that would defeat the purpose. – SumptuaryhasOwnProperty
. – CuccuckoldhasOwnProperty()
was designed. It only checks properties directly on the object, not anywhere in the prototype chain. I can see a rationale for a different function that tells you if the property is on the object or in it's own prototype, but that is not what.hasOwnProperty()
was written to do. You could write such a function. – Ylangylang[[Prototype]]
chain is required, then it is dependent on one ofgetPrototyeOf
,__proto__
or that the constructor property and constructor.prototoype are accurate. But I don't see that there's much benefit to that beyond that provided by typeof. – Hayward[[Prototype]]
chain. – Hayward.hasOwnProperty()
the way it works and many reasons to see if the object has a property in any way, but never encountered a reason to use the function you're asking about in real code. – Ylangylangin
to do the same job, which is fine here. Trying to understand rather than just fix the problem. – Cuccuckold