'this' in function inside prototype function [duplicate]

Solution 1:

sampleObject.prototype.getFoo = function() {
 var me = this;
 var nested = function() {
  return me.foo;
 }
 return nested;
}

By saving the value of this in a local variable, you make it explicitly part of the lexical context for that function and for all nested function scopes. Thus, on the call to "nested", that inner function will have its own scope (it's own this value), but it can still refer to the variable "me" in the enclosing scope.

Solution 2:

In your example "this" refers to the window object because you didn't specify another context when you call the nested function and you get undefind because window.foo is undefined.

You can fix this in 3 ways.

1 - Use a variable to store the outside this - most used method

sampleObject.prototype.getFoo = function() {
 var _this = this;
 var nested = function() {
  return _this.foo;
 }
 return nested();
}

2 - Use the bind method which bind the outer "this" to the inner one

sampleObject.prototype.getFoo = function() {
 var nested = function() {
  return this.foo;
 }.bind(this);
 return nested();
}

3 - Use the call method which can pass the context to the function

SampleObject.prototype.getFoo = function() {
 var nested = function() {
  return this.foo;
 };
 return nested.call(this);
}

Solution 3:

The common work around for that is to use closure

sampleObject.prototype.getFoo = function() {
  var _this = this; 
  var nested = function() {
    return _this.foo;
   }
   return nested();
}

Some libraries add methods to automate this

  • Prototype adds Function.bind (http://prototypejs.org/doc/latest/language/Function/prototype/bind/)
  • Ext adds function.createDelegate (http://www.sencha.com/learn/Manual:Utilities:Function#createDelegate)
  • Javascript 1.8.5 adds function.bind (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind)