2016-08-18 14 views
1

我已经试过这样:JavaScript的数组原型,“这个”没有“推”的方法

// You can pass an array on the addArr method, and each element from the 
// passed array is pushed to the array on which addArr was called. 
Array.prototype.addArr = function(arr){ 
    console.log(this); 

    // As `this` is the array, we use this.push to insert arr's elements 
    arr.forEach(function(elm){ 
    this.push(elm); 
    }); 

    // And then finally return this. 
    return this; 
}; 

的代码已经被使用注释解释,但让我把直。我试图在名为addArrArray对象上创建一个新方法,该方法可以将数组[1, 2, 3]传递给该方法,并将每个元素添加到调用该方法的数组中。

对于e.g

var myArr = [1, 2, 3]; 
myArr.addArr([4, 5, 6]); 
// The output is supposed to be [1, 2, 3, 4, 5, 6] 

我越来越Uncaught TypeError: this.push is not a function,我试图调试,这总是返回父阵列还是它说,push不是一个函数。

我该如何解决?我可以使用像Lodash这样的库,但我不喜欢这样的小应用程序。

谢谢!

+1

'this'是特定于每个功能。 'forEach(function()...)'是一个新的函数,它有自己的'this'值... – deceze

+0

当你调用你的回调函数时,'.forEach()'方法不会*设置'this'。尽管你可以用'arr.forEach(function(){},arr)'来实现。此外,它真的*没有意义的回调添加一个新的元素到你正在迭代的同一个数组。 – nnnnnn

+0

哦,我觉得很愚蠢!甚至没有注意到这一点。非常感谢你们所有人。 –

回答

4

this存储到函数外部的变量中。

Array.prototype.addArr = function(arr){ 
var that = this; 
arr.forEach(function(elm){ 
that.push(elm); 
}); 

    return this; 
}; 
var myArr = [1,2,3]; 
myArr.addArr([4,5]); 

的选择,因为@nnnnnn指出的那样,你可以通过this作为参数传递给.forEach功能。

Array.prototype.addArr = function(arr){ 
arr.forEach(function(elm){ 
this.push(elm); 
},this); 
return this; 
}; 

var myArr = [1,2,3]; 
myArr.addArr([4,5]); 
+0

@DeepakKamat不客气! :-) –

+1

不会'arr.forEach(function(){},this)'比创建一个新变量更容易吗? (forEach()的可选第二个参数指定回调中this的值。) – nnnnnn

+0

@nnnnnn这是真的。不知道它是否会在这里表现很好,但也许它可以被认为是更干净的解决方案:-)我已经改变了我的答案补充说,谢谢! –

相关问题