admin管理员组文章数量:1418590
I am struggling to understand hitch function of the dojo toolkit. I am looking at this example at .10/dojo/_base/lang.html, which is the following:
require(["dojo/_base/lang"], function(lang){
var myObj = {
foo: "bar",
method: function(someArg){
console.log(this.foo);
}
};
var func = lang.hitch(myObj, "method");
func();
});
Is it not possible to utilize that function by myObj.method(arg) instead? Thank you
I am struggling to understand hitch function of the dojo toolkit. I am looking at this example at https://dojotoolkit/reference-guide/1.10/dojo/_base/lang.html, which is the following:
require(["dojo/_base/lang"], function(lang){
var myObj = {
foo: "bar",
method: function(someArg){
console.log(this.foo);
}
};
var func = lang.hitch(myObj, "method");
func();
});
Is it not possible to utilize that function by myObj.method(arg) instead? Thank you
Share Improve this question asked Jul 20, 2016 at 17:10 NaciNaci 2313 silver badges16 bronze badges1 Answer
Reset to default 6Is it not possible to utilize that function by
myObj.method(arg)
instead?
Yes, it is in that particular case, but it's quite mon to need to pass a function reference to other code, and function references don't (by default) carry any particular this
baked into them; this
gets set by how you call the function.
So for instance, if you use myObj.method
as an event handler, when it gets called, this
during the call won't refer to the object myObj
refers to.
hitch
fixes that by creating a new function that, when called, will call your method with this
set correctly.
It's been dated for some time, ES5 (in 2009) introduced Function#bind
, which does the same thing. But the Dojo Toolkit was initially created back in 2005, so it included utilities like this. Here's that same code using Function#bind
instead:
require(["dojo/_base/lang"], function(lang){
var myObj = {
foo: "bar",
method: function(someArg){
console.log(this.foo);
}
};
var func = myObj.method.bind(myObj);
func();
});
Here's a live example demonstrating how it can matter in an event handler:
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">
本文标签: javascriptUnderstanding dojo hitchStack Overflow
版权声明:本文标题:javascript - Understanding dojo hitch - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745290439a2651760.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论