Saturday 26 October 2019

javascript - Why is the "this" value different?





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

Answer




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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...