简体   繁体   中英

Passing more parameters into callback function

I use lodash _.forIn , it has a callback with key and value.

_.forIn({...}, callback);

function callback(key, value) {...}

Is there a way to pass a third parameter to that function?

You could use a HOF (Higher-Order Function) to avoid writing a separate callback with almost the same body.

function createCallback(yourParameter){
    return function(key, value){
        if(yourParameter === 'Something'){
           //doSomething different;
        } else if(yourParameter === 'Something else'){
           //doSomethingElse
        }
    }
}

var cb1 = createCallback('Something');
var cb2 = createCallback('Something else');

_.forIn({...}, cb1);
_.forIn({...}, cb2);

Use partial() for this.

function log() {
    console.log(arguments);
}

var func = _.partial(log, 'hello');

func('world');
// → [ "hello", "world" ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM