简体   繁体   中英

Is it possible to merge these two functions

I have a bunch of functions that look like this

'tea' : function (caller) {
    this.speak(this.randomOption('tea_msg'));

},

'chill' : function (caller) {
    this.speak(this.randomOption('chill_msg'));

},

and what i want is to merge them to something like this

'tea' ,'chill': function (caller) {
     // get which function name was called in var lets call it fun
    this.speak(this.randomOption(fun +'_msg'));
}

Is this possible or am I going about this the wrong way?

You can make a function-maker-function that would get pretty close

function speaker(message){ return function(caller){
    this.speak(this.randomOption(message + '_msg');
};}

{
    'tea': speaker('tea'),
    'chill': speaker('chill')
}

And if you want to avoid retyping the 'tea' and 'chill' you can use the [] object-subscripting syntax together with some sort of loop:

var funs = {};
var msgs = ['tea', 'chill'];
for(var i=0; i<msgs.length; i++){
    var msg = msgs[i];
    funs[msg] = speaker(msg);
}

Just be careful about the closures-inside-for-loops if you want to write the speaker function inline instead.

You could pass the function name as a variable?

'text': function (caller, functionName) {
     // get which function name was called in var lets call it fun
    this.speak(this.randomOption(functionName +'_msg'));
}
[ 'tea', 'chill', 'elephant', 'moose' ].forEach(function (val) {

    //creating a closure so `val` is saved
    (function (val) {
        obj[ val ] = function ( caller ) {
            this.speak( this.randomOption(val + '_msg') );
        };
    }(val));

});

You can also write a generic say function:

say : function ( caller, type ) {
    this.speak( this.randomOption(type + '_msg') );
}

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