下面有一个简单的示例,它创建一个Object构造函数。有一个add
方法试图通过调用arguments
方法来遍历Array.prototype.forEach
集合。
该技术有效,但是我对this
值有疑问。
我采用了将this
分配给实变量(This
)的技巧,即在内部函数中使用实值。可行,但我应该更简单。
根据pandas documentation for the count,我应该可以在开头用一个可选的thisArg
来调用它。我已经在add2
方法中尝试过了。这无效。
在this
方法中为call
参数添加新值的正确方法是什么?
function Collection() {
this.data=[];
}
Collection.prototype={
constructor: Collection,
add() {
var This=this;
Array.prototype.forEach.call(arguments,function(value) {
This.data.push(value);
});
},
add2() {
Array.prototype.forEach.call(this,arguments,function(value) {
this.data.push(value);
});
},
}
var c=new Collection();
c.add('apple','banana');
alert(c.data)
答案 0 :(得分:1)
forEach
使用this
的可选参数,它将在回调中使用。如果您不能使用箭头功能,这应该是一个不错的选择:
function Collection() {
this.data=[];
}
Collection.prototype={
constructor: Collection,
add2() {
Array.prototype.forEach.call(arguments,function(value) {
this.data.push(value);
}, this); // <= pass this in to forEach
},
}
var c=new Collection();
c.add2('apple','banana');
console.log(c.data)