Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript calling function inside another mystery

Tags:

javascript

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

like image 313
xdevel2000 Avatar asked Jul 11 '26 04:07

xdevel2000


2 Answers

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.

like image 137
annakata Avatar answered Jul 13 '26 20:07

annakata


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);
}
like image 29
MX. Avatar answered Jul 13 '26 20:07

MX.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!