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 badges
Add a ment  | 

1 Answer 1

Reset to default 6

Is 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