我定义为阵列中的两个功能:如何在内部函数中调用外部“this”?
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);
});
}
但它很丑。有没有更好的办法?
我不认为这是非常难看的,而且很有效。你的foreach中的'this'变成迭代中的项目,所以我没有看到太多的解决方法。 – Paddy 2011-12-23 09:29:02