Daniel Robinson
Daniel Robinson

Reputation: 14878

javascript hasOwnProperty

I'm trying to get some of my types to have a kind of multiple 'inheritance' like so:

UIControls.ClickableMesh.prototype = Object.create(THREE.Mesh.prototype);

var UIConProto = Object.create(UIControls.UIControl.prototype);

for(var i in UIConProto){
    if(UIConProto.hasOwnProperty(i)){
        UIControls.ClickableMesh.prototype[i] = UIConProto[i];
    }
}

But the for loop isn't adding any of UIControls.UIControl.prototype properties to my new types prototype UIControls.ClickableMesh.prototype. Why is hasOwnProperty returning false for eveything? there should be some members of it which are directly of the object.

Upvotes: 0

Views: 1271

Answers (2)

Dale Z
Dale Z

Reputation: 517

hasOwnProperty only returns true when the property belongs to the object itself, instead of inheriting from its prototype. For instance:

function Foo() {
  this.n = 123;
}
Foo.prototype.s = "hello";

var foo = new Foo();

foo.hasOwnProperty("s"); // False, since s is inherited from the prototype object.
foo.hasOwnProperty("n"); // True, since n is the property of foo itself.

You may notice the way Object.create() create your object, which falls into the first category of the sample above.

Upvotes: 3

c-smile
c-smile

Reputation: 27460

hasOwnProperty ... unlike the in operator, this method does not check down the object's prototype chain.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Objects in JS are hash-maps and the sole purpose of the hasOwnProperty is to check if that hash-map contains that property. hasOwnProperty does not traverse __proto__ chain.

Upvotes: 2

Related Questions