我为数组定义了两个函数:
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
是惯用的方法。没有什么丑陋的。 (虽然更常见的是调用变量 that
或 self
)
关于javascript - 如何在内部函数中调用外部 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8614256/