Saturday, October 26, 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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...