Javascript "this" pointer within nested function

Solution 1:

In JavaScript the this object is really based on how you make your function calls.

In general there are three ways to setup the this object:

  1. someThing.someFunction(arg1, arg2, argN)
  2. someFunction.call(someThing, arg1, arg2, argN)
  3. someFunction.apply(someThing, [arg1, arg2, argN])

In all of the above examples the this object will be someThing. Calling a function without a leading parent object will generally get you the global object which in most browsers means the window object.

Solution 2:

Since this appears to be among the most upvoted questions of its kind, let me add, after all these years, the ES6 solution using arrow functions:

var std_obj = {
  ...
  displayMe() {
    ...
    var doSomeEffects = () => {
                        ^^^^^^^    ARROW FUNCTION    
      // In an arrow function, the 'this' pointer is interpreted lexically,
      // so it will refer to the object as desired.
      if (this.activeEffect=="fade") { }
    };
    ...    
  }
};

Solution 3:

this is not part of the closure scope, it can be thought of as an additional parameter to the function that is bound at the call site. If the method is not called as a method then the global object is passed as this. In the browser, the global object is identical to window. For example, consider the following funciton,

function someFunction() {
}

and the following object,

var obj = { someFunction: someFunction };

If you call the function using method syntax such as,

obj.someFunciton();

then this is bound to obj.

If you call someFunction() directly, such as,

someFunction();

then this is bound to the global object, that is window.

The most common work around is to capture this into the closure such as,

displayMe : function() {      

    // the 'this' pointer is referring to the std_obj      
    if (this.activeEffect=="fade") { }      
    var that = this;  
    var doSomeEffects = function() {      

      // the 'this' pointer is referring to global
      // that, however, refers to the outscope this
      if (that.activeEffect=="fade") { }      
    }      

    doSomeEffects();         
 }