0

I want to use this in a callback function in a prototype method eg.:

String.prototype.new= function (data) {
    'use strict';
    //here I can use 'this'
    Object.getOwnPropertyNames(data).forEach(function (d) {
        //here I want to use 'this' but I can't
    });
};

See the comments above: How do I use this within the callback?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
user4230877
  • 109
  • 6

1 Answers1

0

forEach accepts a second argument, which tells it what to use for this during the callbacks, so:

String.prototype.new= function (data) {
    'use strict';
    //...
    Object.getOwnPropertyNames(data).forEach(function (d) {
        //...
    }, this);
//   ^^^^^^--------------- added
};

Almost all of the new ES5 Array methods have that thisArg argument.

If you were using something that didn't have an argument it used that way (for instance, the old Array#sort function), you could use a variable you save this to and then use the variable in the callback:

String.prototype.new= function (data) {
    'use strict';
    var thisString = this;

    //...
    someArray.sort(function(a, b) {
        // use `thisString` here
    });
};
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875