将function.call与该参数一起用作函数参数

时间:2018-10-06 01:41:06

标签: javascript arrays arguments this

下面有一个简单的示例,它创建一个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)

1 个答案:

答案 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)