user4230877 user4230877 - 1 year ago 39
Javascript Question

How to access `this` object in callback function inside prototype method?

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?

Answer Source

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
    });
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download