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

标签 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!!
    });
}

但是在removeAll函数中,报function remove is not found。我这样修复它:

Array.prototype.removeAll = function(array2) {
    var outer = this;
    array2.forEach(function(item) {
        outer.remove(item);  
    });
}

但是很丑。有没有更好的办法?

最佳答案

通过不同的变量传递 this 是惯用的方法。没有什么丑陋的。 (虽然更常见的是调用变量 thatself)

关于javascript - 如何在内部函数中调用外部 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614256/

相关文章:

javascript - 插入符号 (^) 在 JavaScript 中有什么作用?

javascript - 防止 react 简单 map 中的蓝色路径矩形

javascript - 如何在 Highchart 中自定义工具提示?

python - 函数如何访问自己的属性?

c - c中函数没有返回值

ios - 如何停止这个序列?

Javascript 包括不在页面中稍后加载

javascript - 有没有办法查看是什么在操纵 HTML 节点?

C - "mixedly allocated"数组的调用函数

javascript - 嵌套在 if 语句中的函数