Why does hasOwnProperty not recognise functions on an object's prototype?

glenatron picture glenatron · Mar 17, 2014 · Viewed 17.4k times · Source

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?

Answer

elclanrs picture elclanrs · Mar 17, 2014

I think you're confusing a few concepts here. Let's take this quote from the MDN:

Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

So that's the key here. When you use new JavaScript will assign a brand new object to this and return it, that's what an instance is. Any property declared inside the constructor is an own property. Properties declared on the prototype are not, since they are shared with other instances of the same object.

And a prototype is also an Object, for example:

Bob.prototype.hasOwnProperty("sayHello"); //=> true

myBob.constructor.prototype.hasOwnProperty("sayHello"); //=> true