Pergunta

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?

Foi útil?

Solução

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

Outras dicas

I understand that the hasOwnProperty method in JavaScript exists to identify properties only of the current type

That is not correct. hasOwnProperty identifies own properties of an object, that is, properties of the object itself. It does not consider inherited properties on an object's [[Prototype]] chain.

e.g.

var foo = {name: 'foo'};

// Check for an own property
foo.hasOwnProperty('name'); // true

The object foo also inherits a toString method from Object.prototype, but it's not an "own" property:

typeof foo.toString             // function
foo.hasOwnProperty('toString'); // false
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top