如何在原型方法中的回调函数中访问`this`对象?

时间:2015-03-29 12:04:37

标签: javascript

我想在原型方法的回调函数中使用this,例如:

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

请参阅上面的评论:如何在回调中使用this

1 个答案:

答案 0 :(得分:0)

forEach接受第二个参数,该参数告诉它在回调期间用于this的内容,所以:

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

几乎所有 ES5 Array方法都有thisArg个参数。

如果您使用的某些内容没有有一个以这种方式使用的参数(例如,旧的Array#sort函数),您可以使用保存的变量{ {1}}然后在回调中使用变量:

this
相关问题