了解道场挂钩

Understanding dojo hitch

我很难理解 dojo 工具包的挂接功能。我正在 https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html 查看此示例,如下所示:

require(["dojo/_base/lang"], function(lang){
var myObj = {
    foo: "bar",
    method: function(someArg){
      console.log(this.foo);
    }
  };

  var func = lang.hitch(myObj, "method");

  func();
});

是否无法通过 myObj.method(arg) 来使用该功能?谢谢

Is it not possible to utilize that function by myObj.method(arg) instead?

是的,在那种特殊情况下,但是需要将函数引用传递给其他代码是很常见的,并且函数引用不会(默认情况下)携带任何特定的 this ; this 由您调用函数的方式设置。

因此,例如,如果您使用 myObj.method 作为事件处理程序,当它被调用时,调用期间的 this 将不会引用 myObj 所引用的对象。

hitch 通过创建一个新函数来修复该问题,该函数在被调用时将调用您的方法并正确设置 this

它已经过时了一段时间,ES5(2009 年)引入了 Function#bind,它做同样的事情。但 Dojo Toolkit 最初是在 2005 年创建的,因此它包含这样的实用程序。这是使用 Function#bind 代替的相同代码:

require(["dojo/_base/lang"], function(lang){
  var myObj = {
    foo: "bar",
    method: function(someArg){
      console.log(this.foo);
    }
  };

  var func = myObj.method.bind(myObj);

  func();
});

这是一个演示它在事件处理程序中的重要性的实例:

var obj = {
  foo: "bar",
  method: function() {
    console.log("this.foo = " + this.foo);
  }
};
document.getElementById("unbound").addEventListener("click", obj.method, false);
document.getElementById("bound").addEventListener("click", obj.method.bind(obj), false);
<input type="button" id="unbound" value="Unbound">
<input type="button" id="bound" value="Bound">