Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the "this" value different? [duplicate]

Here is an example where o.foo(); is 3 but (p.foo = o.foo)(); is 2?

function foo() {
    console.log( this.a );
}

var a = 2;
var o = { a: 3, foo: foo };
var p = { a: 4 };

o.foo(); // 3
(p.foo = o.foo)(); // 2”

If I do something like this then I get 4 which is what I want. How are those 2 examples are different?

p.foo = o.foo;
p.foo();  // 4
like image 405
Alexey Tseitlin Avatar asked Dec 07 '22 15:12

Alexey Tseitlin


1 Answers

This :

(p.foo = o.foo)();

Is pretty much the same as doing this:

d = (p.foo = o.foo);
d();

Basically what it says is that the return of an assignment is the function itself in the global context. On which a is 2.

like image 70
Julien Grégoire Avatar answered Dec 11 '22 10:12

Julien Grégoire