[removed] Configuration Pattern

前端 未结 3 1274
情话喂你
情话喂你 2020-12-18 07:07

Problem: A Javascript function needs few parameters to work with:

function kick(person, reason, amount) {
    // kick the *person* with the         


        
3条回答
  •  余生分开走
    2020-12-18 07:59

    You don't have to go strictly with any of the three. If you look at how jQuery does it, it examines the type and quantity and position of the parameters to figure out which overloaded flavor of the function is being used.

    Suppose you had three flavors of kick(), one that takes person, reason and amount and one that takes just person with reason and amount getting default values and one that takes a config object with at least a person on it. You could dynamically see which of the three options you had like this:

    function kick(person, reason, amount) {
        if (person.person) {
           // must be an object as the first parameter
           // extract the function parameters from that object
           amount = person.amount;
           reason = person.reason;
        }
        amount = amount || 5;           // apply default value if parameter wasn't passed
        reason = reason || "dislike";   // apply default value if parameter wasn't passed
        // now you have person, reason and amount and can do normal processing
        // you could have other parameters too
        // you just have to be to tell which parameter is which by type and position
    
        // process the kick here using person, reason and amount
    }
    

提交回复
热议问题