在javascript中将方法作为参数传递的惯用法

时间:2014-10-05 13:31:22

标签: javascript methods binding

// This didn't work because "this" in display_previous_room was Window instead of a Collection object.
this.listener.simple_combo("left",this.collection.display_previous_room);

// This worked
this.listener.simple_combo("right",this.collection.display_next_room.bind(this.collection));

这是在javascript中执行此操作的正确方法吗?或者我应该更改this.listener.simple_combo(这是第三方库)以允许调用者添加像这样的方法参数

this.listener.simple_combo("right",this.collection.display_next_room,this.collection,{...}); // simple_combo(key,function/method,binding,arguments to the function/method)

1 个答案:

答案 0 :(得分:1)

您可以像这样绑定Collection对象

this.listener.simple_combo("right", this.collection.display_next_room.bind(this.collection));

以便this将引用正确的集合对象。