function Obj1(param) { this.test1 = param || 1; }
function Obj2(param, par)
{
this.test2 = param;
this.ob = Obj1;
this.ob(par);
}
now why if I do:
alert(new Obj2(44,55).test1);
the output is 55? how can 'view' test1 an Obj2 istance if I haven't link both via prototype chain?
Thanks
Well it's not clear what you want but the reason this happens is because here:
this.ob = Obj1;
you add the Obj1 method to the object instance of Obj2, and when you use it here:
this.ob(par);
the context of "this" inside the method Obj1 is the Obj2 instance. So that instance now has a test1 member.
Nothing to do with inheritance really, but it's a bit like a mix-in. Remember in JS functions are first class objects.
Let think about Obj1 as a function. So, when you do
function Obj2(param, par)
{
this.test2 = param;
this.ob = Obj1;
this.ob(par);
}
your code become identical to the following code:
function Obj2(param, par)
{
this.test2 = param;
this.ob = function (param) { this.test1 = param || 1; }
this.ob(par);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With