简体   繁体   English

箭头 function 避免绑定

[英]Arrow function to avoid bind

var world = {
  animals: {},
  add_animal: function(options) {
    this.animals[options.name] = {
      name: options.name,
      sound: options.sound,
      actions: {},
      add_action: function(action_name, action_function) {
        this.actions[action_name] = action_function.bind(this);
      }
    }
  }
};

world.add_animal({name: "dog", sound: "bark"});
world.animals.dog.add_action("speak", function() {
  alert("I am a " + this.name + ". I " + this.sound + ".");
});

world.animals.dog.actions.speak();

This is a simplified version of a script I wrote a few years ago, which I'd like to update.这是我几年前编写的脚本的简化版本,我想对其进行更新。 It creates a world object, with a collection of animals and an add_animal method.它创建了一个包含动物集合和 add_animal 方法的世界 object。 Each animal has an add_action method.每个动物都有一个 add_action 方法。 I'd appreciate some advice on two things.我很感激关于两件事的一些建议。

  1. add_action uses bind so "this" refers to the animal within the action function - is there a way to do this with an arrow function => so there's no need for bind? add_action 使用绑定,所以“this”指的是动作 function 中的动物 - 有没有办法用箭头 function => 所以不需要绑定?

  2. I figured there'll only ever be one "world" so that's why I started with an object literal for world, rather than making world a class.我认为永远只有一个“世界”,所以这就是为什么我从世界的 object 文字开始,而不是让世界成为 class。 Is there another "best practice" way this could be done, perhaps using classes?是否有另一种“最佳实践”方式可以做到这一点,也许使用类? If so, is there any real advantage in doing it another way?如果是这样,以另一种方式做有什么真正的优势吗?

  1. add_action uses bind so "this" refers to the animal within the action function - is there a way to do this with an arrow function => so there's no need for bind? add_action 使用绑定,所以“this”指的是动作 function 中的动物 - 有没有办法用箭头 function => 所以不需要绑定?

Not if you want to use this within the action function to refer to the animal, no.如果您想在操作 function 中使用this来指代动物,则不是。

  1. I figured there'll only ever be one "world" so that's why I started with an object literal for world, rather than making world a class.我认为永远只有一个“世界”,所以这就是为什么我从世界的 object 文字开始,而不是让世界成为 class。 Is there another "best practice" way this could be done, perhaps using classes?是否有另一种“最佳实践”方式可以做到这一点,也许使用类? If so, is there any real advantage in doing it another way?如果是这样,以另一种方式做有什么真正的优势吗?

If world is a singleton, there's usually no need to do anything other than what you've done.如果world是 singleton,那么除了你已经完成的事情之外,通常不需要做任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM