如何在内部函数中调用外部"this"?

Fre*_*ind 5 javascript function

我为数组定义了两个函数:

Array.prototype.remove = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            this.removeAt(i);
        }
    }
};
Array.prototype.removeAll = function(array2) {
    array2.forEach(function(item) {
        this.remove(item);  // remove not found!!
    });
}
Run Code Online (Sandbox Code Playgroud)

但在removeAll功能方面,它报道function remove is not found.我修复它像这样:

Array.prototype.removeAll = function(array2) {
    var outer = this;
    array2.forEach(function(item) {
        outer.remove(item);  
    });
}
Run Code Online (Sandbox Code Playgroud)

但它很难看.有没有更好的办法?

Que*_*tin 6

this通过不同的变量传递是惯用的方法.它没什么难看的.(调用变量that或更常见self)