Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indirect references to functions in javascript

Tags:

javascript

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.

like image 759
Alexander Solonik Avatar asked Oct 20 '25 05:10

Alexander Solonik


2 Answers

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();
like image 195
Steve Mitcham Avatar answered Oct 21 '25 19:10

Steve Mitcham


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.

  1. p.foo = o.foo;
  2. foo();
like image 36
Simon Avatar answered Oct 21 '25 18:10

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!