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

前端 未结 7 1690
甜味超标
甜味超标 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 07:56
    //why not just:
    (function($){
      $.hitch = function(scope, fn){
        return function(){
          return fn.apply(scope, arguments);
        }
      }
    })(JQuery);
    //This works exactly like Dojo's hitch from what I can tell.
    
    0 讨论(0)
  • 2021-02-07 08:04

    I know this has been answered, but not correctly. jQuery.proxy is what you are looking for I believe.

    UPDATE

    Many, many years later after lots of JavaScript work, and after stripping out my usage of jQuery since browser compatibility has become less of an issue, I would recommend using Function.prototype.bind over jQuery.proxy, as @bobince suggested. While this is still the correct answer to the original question, I feel obligated to direct people to a vanilla solution rather than relying on jQuery.

    0 讨论(0)
  • 2021-02-07 08:07

    [ADMIN EDIT: Note the much more popular answer, below.—danorton]

    I'd go for function.bind, which will be the standard way of doing this in future versions of JavaScript. As well as fixing this , it allows you to pass arguments through to the target functions.

    Until all browsers support it natively, you can hack support in yourself.

    0 讨论(0)
  • 2021-02-07 08:08
    /**
     * This is for simulate dojo.hitch.
     * @param $
     */
    (function($) {
        $.hitch = function(context, func) {
            var args = Array.prototype.slice.call(arguments, 
                    2/*Remove context, and func*/);
    
            return function() {
                return func.apply(context, 
                        Array.prototype.concat.call(args, arguments));
            };
        };
    })(jQuery);
    
    0 讨论(0)
  • 2021-02-07 08:11

    No. Not in 1.3.2, at least, as I don't know about 1.4. There are, however, some plugins:

    (function($) {
      $.fn.hitch = function(ev, fn, scope) {
        return this.bind(ev, function() {
          return fn.apply(scope || this, Array.prototype.slice.call(arguments));
        });
      };
    })(jQuery);  
    
    0 讨论(0)
  • 2021-02-07 08:13

    In my mind, hitch in Dojo is more complex,

    e.g.,

    function f(a,b,c){return a+b*c}
    var newF = hitch(null,f,1,undefined,3);
    newF(2) /*1+2*3*/
    
    0 讨论(0)
提交回复
热议问题