Search code examples
javascriptclosuresself-invoking-function

Confusing scope and self invocations in JavaScript


Let's look at this example:

var x = 3;

var obj = {
  x:2,
  test: function(){
    var x = 1;
    console.log(this.x);
  } 
};

And then we have different ways to call this function:

obj.test(); // line 1

obj.test.call(null); // line 2

(obj.test)(); // line 3

(obj.test = obj.test)(); // line 4

(obj.test || obj.test)(); // line 5

(obj.test && obj.test)(); // line 6

(obj.test, obj.test)(); // line 7

I understand first 3 lines but can anyone explain me what is going on further ( line 4 to 7 ). That is confusing.


Solution

  • From 4 to 7 in each case it returns the function only, not the context. So when you have grabbed the function from the object, it loses it's context.And then it tries to call the function, the this in it refer to the global object, which is the window and x in window is 3. So in use strict mode it will be null, in other mode it will be the window.

    4) Assign the right hand value to the left hand value and return it

    (obj.test = obj.test)()
    

    5) If the first operand is true, return it, else return the second operand

    obj.test || obj.test
    

    6) If the first and second operands are true, return the first operand, else return the second operand

    obj.test && obj.test
    

    7) In this case it only returns the second object. , comma only separates the object from each other

    (obj.test, obj.test)()