My understanding is that "hasOwnProperty" returns true if the object has a given member without check the prototype chain. But when I inherit fro other object, I see all members in the last object itself.
Consider the following example:
var Object1 = function (param) {
this.prop1 = "p1 " + param;
this.prop2 = "p2 " + param;
};
var Object2 = function (param) {
Object1.apply(this, arguments);
this.prop3 = 'p3' + param;
};
Object2.prototype = new Object1();
var b = new Object2('this is Object 2');
for (var v in b)
print(v + ": " + b[v] + (b.hasOwnProperty(v)?' (own)':' (inherited)'));
This code prints:
--prop1: p1 this is Object 2 (own)
--prop2: p2 this is Object 2 (own)
--prop3: p3this is Object 2 (own)
If I take a look on the debugger I see:
b
Object2
prop1: "p1 this is Object 2"
prop2: "p2 this is Object 2"
prop3: "p3this is Object 2"
__proto__: Object1
But, id I remove the apply
line, all makes more sense, but base object it is not initialized:
--prop3: p3this is Object 2 (own)
--prop1: p1 undefined (inherited)
--prop2: p2 undefined (inherited)
Now I see in the debugger:
b
Object2
prop3: "p3this is Object 2"
__proto__: Object1
prop1: "p1 undefined"
prop2: "p2 undefined"
__proto__: Object
As far as I know, apply
it's like ... execute the super class constructor, so super members are initialized correctly, but apparently that changes the shape of the child object.
Why is this happening? What is the correct way -or at least the less messy- to inherit in JS?
I am taking a look to some information about it, and apparently each developer has different feelings about how to do it.
Regards.