开发者

'this' in function inside prototype function [duplicate]

This question already has answers here: How to access the correct `this` inside a callback (13 answers) Closed 3 years ago.

I basically have an object, extended with a function through its prototype. Inside that function, another function exists, however when using this in this nested function, it does not seem to refer to the object, but the function.

For example,

var sampleObject = function() {
 t开发者_StackOverflow中文版his.foo = 123;
}

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

var test = new sampleObject();

window.alert(test.getFoo()); // undefined

The this.foo does not refer to the 123 value, but is undefined as this refers to the nested function, in which no foo exists. How can I access the 123 value from the nested function?


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.


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);
}


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)


tl;dr

Use arrow functions. They are available since ECMAScript 6:

var sampleObject = function() {
  this.foo = 123;
}

sampleObject.prototype.getFoo = function() {
  var nested = () => { // Changed this line.
    return this.foo;
  }
  return nested();
}

var test = new sampleObject();

window.alert(test.getFoo());

Explanation

This is one of the main advantages of arrow functions. Your case is described in the section: No binding of this. The refference states:

Until arrow functions, every new function defined its own this value [...] An arrow function does not create its own this context, so this has the original meaning from the enclosing context.


Apart from declaring it to var _this = this, I also see codes doing var that = this or var self = this.

Knowing your variable's scope is important as it might raises unexpected result.


This is an old question, but I give another solution for the sake of completeness. Another approach involves function binding.

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


An ES6 way of doing this would be to use an Arrow Function. Basically, when you use an arrow function, it does not create it's own "this" context. So, using "this" would then refer to the parent function's context. Here's how the code would look:

sampleObject.prototype.getFoo = function() {
    const nested = () => {
        return this.foo; //"this" refers to parent function's context
    }
    return nested;
}


This is a known wart on JavaScript. The usual pattern is to assign this to another variable (often self) in the outer function, then access self from the inner funtction. This works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜