0

I am trying to understand what is going "under the hood". Other questions dont explain the mechanics I am interested it. Please see code under.

I am looking for steps like this:

  1. (p.foo = o.foo)(); expresion
  2. Value of o.foo is hold somewhere and is not yet related to p obj?
  3. Value of o.fooget executed?
  4. p.foo gets the value on o.foo?

is this right? if yes then need more info in step 2 on how, where and why...

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)(); // we get 2 and not 4”
Alexey Tseitlin
  • 821
  • 1
  • 11
  • 22
  • When you want to get `4` instead of `2` then you need to do this: `o.foo.call(p);` or `(p.foo = o.foo.bind(p))()` then `foo` is executed in the context of `p` and not in the context of `window` as `var a = 2;` is assigned to (in the last row) – Blauharley Apr 22 '18 at 16:55
  • 1
    It should be obvious from the grouping that the assignment happens before the function call – Bergi Apr 22 '18 at 16:57
  • possible duplicate of https://stackoverflow.com/q/45558692/1048572 – Bergi Apr 22 '18 at 17:01
  • Possible duplicate of [why 'this' point to 'window' obj when using assignment operator in iife?](https://stackoverflow.com/questions/45558692/why-this-point-to-window-obj-when-using-assignment-operator-in-iife) – Mark Apr 22 '18 at 17:02
  • There are no steps explaining the mechanics in those other questions =(( – Alexey Tseitlin Apr 22 '18 at 17:03
  • 1
    @AlexeyTseitlin What do you mean by "mechanics"? How the expression is parsed, or how it is evaluated? What exactly is unclear? – Bergi Apr 22 '18 at 20:48

2 Answers2

0

There is nothing special happening here.

This line

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

is equivalent to executing below function in global scope(this refers to window) where value of a is 2 which gets printed.

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

following assignment returns function definition

p.foo = o.foo 

its not executing foo on p or o object. its just adding property foo on p object and assigning it that function.

Hence , you end up executing code in global scope

   (function () {
    console.log( this.a );
})()
faizan
  • 152
  • 1
  • 9
0

p.foo = o.foo is an expression. All expressions resolve to a value. In this case, it's the function foo().

So basically, when you call this code, you not only assign a new value to p.foo (because it so happens that the expression contains the assignment operator =) -- you also get back the global function foo as a result of evaluating the expression.

You then call the function inline in the window context, where a equals to 2.