我一直在发疯,试图弄清楚如何使此代码正常工作。我的目标是通过将larry eats pie, larry eats candy, larry eats cake对象中的功能eats绑定到alice对象来产生输出larry。我对下面的代码的希望是,将alice.eats函数绑定到larry对象将使用larry作为this.name,然后使用larryFoods数组应用该函数,我希望它将产生每个参数。

//-----------------Does not work--------------//
var alice = {
      name: "alice",
      speak: function(){
      console.log("Hi, I'm " + this.name);
      },
      eats : function(){
        var theArgs = Array.prototype.slice.call(arguments);
        theArgs.forEach(function(arg){
          console.log(this.name + " eats " + arg);
        });
      }
};
var larry = {
    name: "larry"
};
var larrySpeak = alice.speak.bind(larry);
larrySpeak();
var larryFoods = [" pie", " candy", " and cake"];
var larryEats = alice.eats.bind(larry);
larryEats.apply(larryFoods);


我假设forEach函数将在全局上下文中运行,这就是为什么我希望larry eats + [food]将解决问题。任何见解将是最欢迎的。

最佳答案

this函数中,forEach的作用域不属于eats内部的“人”。或视觉上:

theArgs.forEach(function(arg){
    // "this".name is trying to resolve name according to the scope of the forEach
    console.log(this.name + " eats " + arg);
});


您可以在eats函数内部修复此问题:

var scope = this;
theArgs.forEach(function(arg){
    console.log(scope.name + " eats " + arg);
});


最后,您将需要在最后一行修正对apply的使用。 apply需要上下文绑定。由于您已经将函数绑定到larry,因此可以将null作为第一个参数传递:

这个:

larryEats.apply(larryFoods);


应该:

larryEats.apply(null, larryFoods);




解决这些问题后,这是一个有效的示例:



var alice = {
  name: "alice",
  speak: function() {
    console.log("Hi, I'm " + this.name);
  },
  eats: function() {
    var theArgs = Array.prototype.slice.call(arguments);
    var scope = this;
    theArgs.forEach(function(arg) {
      console.log(scope.name + " eats " + arg);
    });
  }
};
var larry = {
  name: "larry"
};
var larrySpeak = alice.speak.bind(larry);
larrySpeak();
var larryFoods = ["pie", "candy", "and cake"];
var larryEats = alice.eats.bind(larry);
larryEats.apply(null, larryFoods);

10-07 21:26