How to pass context to anonymous function?

后端 未结 2 1601
灰色年华
灰色年华 2021-01-31 17:15

There are some function, thats do something long work and its provides callback.

someFunc: function(argument, callback, context) {
  // do something long

  // c         


        
2条回答
  •  终归单人心
    2021-01-31 17:50

    The accepted answer seems somewhat outdated. Assuming you're operating on a relatively modern browser, you can use Function.prototype.bind in vanilla javascript. Alternatively, if you are using underscore or jQuery, you can use _.bind or $.proxy respectively (which will fallback to call/apply if necessary).

    Here is a simple demonstration of these three options:

    // simple function that takes another function
    // as its parameter and then executes it.
    function execute_param(func) {
        func();
    }
    
    // dummy object. providing an alternative context.
    obj = {};
    obj.data = 10;
    
    // no context provided
    // outputs 'Window'
    execute_param(function(){
        console.log(this);
    });
    
    // context provided by js - Function.prototype.bind
    // src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
    // outputs 'Object { data=10 }''
    execute_param(function(){
        console.log(this);
    }.bind(obj));
    
    // context provided by underscore - _.bind
    // src: http://underscorejs.org/#bind
    // outputs 'Object { data=10 }'
    execute_param(_.bind(function(){
        console.log(this);
    },obj));
    
    // context provided by jQuery - $.proxy
    // src: http://api.jquery.com/jQuery.proxy/
    // outputs 'Object { data=10 }'
    execute_param($.proxy(function(){
        console.log(this);
    },obj));
    

    You can find the code in a jsfiddle here: http://jsfiddle.net/yMm6t/1/ (note: ensure that the developer console is open, or you won't see any output)

提交回复
热议问题