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?