Why is the meaning of "this" different?

Here is an example, where o.foo();is 3, but (p.foo = o.foo)();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"
Run codeHide result

If I do something like this, I get 4what I want. How do these two examples differ?

p.foo = o.foo;
p.foo();  // 4
+4
source share
3 answers

It:

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

Just like this:

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

This basically suggests that returning the destination is the function itself in a global context. Which ais equal to 2.

+5
source

Performing this assignment operation before calling the function here:

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

leads to the loss of the reference to the object p. If you wrote instead

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

4. , 2, this window .

, - - . , this , this window ( ).

+4

, , : console.log( this.a );

, .

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

this , .

so you set a=2globally and then to objects o.a = 3andp.a=4

So:

the call o.fooreturns 3because it indicateso

the call p.fooreturns 4because it indicatesp

BUT

(p.foo = o.foo)();it will return the call 2because it does not point to any object, so it will take your scope (which is the global scope), and then it will return 2.

if you follow these steps:

p.foo = o.foo
p.foo() //4

it will return 4 successfully because it points to p.

+4
source

Source: https://habr.com/ru/post/1696253/


All Articles