我很难理解 dojo 工具包的 Hook 功能。我在 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">
关于javascript - 了解道场 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38486750/