3

I found this code in a book:

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

What does last line mean?

Andy
  • 61,948
  • 13
  • 68
  • 95

1 Answers1

5

The last line is doing an assignment and then calling the function.

Assignment happens first

(p.foo = o.foo)

Then call the function

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

In this second call to foo, it is being called outside of the scope of p or o, so it's essentially the same as calling:

foo();
ohiodoug
  • 1,493
  • 1
  • 9
  • 12
  • is this equal to p.foo = o.foo; p.foo(); – user1272913 Dec 28 '15 at 00:00
  • but if you run the code (p.foo = o.foo)(); prints 2 p.foo = o.foo; p.foo(); prints 4 – user1272913 Dec 28 '15 at 00:03
  • 1
    @user1272913: They're not equivalent. The value of `this` in the function invocation will be the `window` object because the function, as the result of the parens, is detached from any object. It's more equivalent to `var f = (p.foo = o.foo); f();` –  Dec 28 '15 at 00:08
  • If you call p.foo(), you are calling it on the p object in which the variable a is scoped to p. In the example `(p.foo = o.foo)();` you are assigning a function and then calling it outside of the scope of either variable, therefore making it use the variable a defined with a value of 2. – ohiodoug Dec 28 '15 at 00:10
  • "you are assigning a function and then calling it outside of the scope of either variable," I am assigning it to p.foo right? and then call p.foo??? – user1272913 Dec 28 '15 at 00:10
  • Updated my answer a bit, I didn't initially notice the values you were asking about. – ohiodoug Dec 28 '15 at 00:12
  • @user1272913: when you do `p.foo()`, the value of `this` inside the `foo` method is the `p` object. This happens automatically. If you detach the `foo` function from the `p` object before invoking it, the value of `this` gets set to the `window` object by default. Your `a` variable is a global variable, so it appears as a property of `window`, and so you get `2`. –  Dec 28 '15 at 00:13
  • You're assigning a reference to a function and then calling that function. – ohiodoug Dec 28 '15 at 00:14
  • 1
    ok I think I got it: this is equivalent to: c=p.foo=o.foo;c() – user1272913 Dec 28 '15 at 00:16