does jquery have an equivalent of dojo.hitch()?

前端 未结 7 1703
甜味超标
甜味超标 2021-02-07 07:24

Forgive my ignorance as I am not as familiar with jquery. Is there an equivalent to dojo.hitch()? It returns a function that is guaranteed to be executed in the given scope.

相关标签:
7条回答
  • 2021-02-07 08:18

    The function.bind mentioned by bobince is a pretty useful tool. You could use it to rewrite the hitch function pretty simply:

    // The .bind method from Prototype.js 
    if (!Function.prototype.bind) { // check if native implementation available
      Function.prototype.bind = function(){ 
        var fn = this, args = Array.prototype.slice.call(arguments),
            object = args.shift(); 
        return function(){ 
          return fn.apply(object, 
            args.concat(Array.prototype.slice.call(arguments))); 
        }; 
      };
    }
    
    jQuery.hitch = function(scope, fn) {
      if (typeof fn == "string") fn = scope[fn];
      if (fn && fn.bind) return fn.bind(scope);
    };
    

    At least based on the doc page you linked, this is how I saw the function working...

    0 讨论(0)
提交回复
热议问题