[removed] Passing parameters to a callback function

后端 未结 13 2470
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 15:48

I\'m trying to pass some parameter to a function used as callback, how can I do that?

function tryMe (param1, param2) {
    alert (param1 + \" and \" + param         


        
13条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 16:12

    Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

    function tryMe (param1, param2) {
        alert (param1 + " and " + param2);
    }
    
    function callbackTester (callback) {
        callback();
    }
    
    callbackTester(tryMe.bind(null, "hello", "goodbye"));
    

    You can also use the following code, which adds the method if it isn't available in the current browser:

    // 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))); 
        }; 
      };
    }
    

    Example

    bind() - PrototypeJS Documentation

提交回复
热议问题