I was just reading the book, "You don't know JS" by kyle simpson and came across the following sinppet of code that somewhat confused me. basically I was reading a topic on the this
keyword. below is the snippet:
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
So far reading the book I do understand how this works, but for me its hard to understand whats really happening on the last line of the snippet.
if I analysis it bymyself the last line is an iffe executing in the global scope and if in the iffe the foo() fuction executes, the this.a in the foo() function will point to the a in the global scope, which is indeed 2.
But somehow I don't feel i totally understand whats happening on the last line, can somebody break it down for me?
Thank you.
Alexander.
The final line is passing along the reference to the foo
function and then executing in the global scope, just as you see. It is equivalent to this
var f = p.foo = o.foo;
f();
The return value of an assignment is always the value itself. At this example the return value is a reference to the function foo. Therefore two steps are executed on one line.
p.foo = o.foo;
foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With