Last Updated: February 25, 2016
·
745
· francesco

easytip: an object as a function of its messages.

I just found this one, not really a stunning pattern, but it could be useful for someone that needs to use just one function name to multiple purposes:

var adam = (function() {
    var firstname = "Adam";
    var lastname = "of Eden";
    return function(message) {
        switch (message) {
        case "getFirstName":
            return firstname;
        case "getLastName":
            return lastname;
        case "getFullName":
            return firstname + " " + lastname;
        default:
            throw "unknown message: " + message;
        }
    };
}());

adam("getFirstName"); // "Adam"
adam("getLastName"); // "of Eden"
adam("getFullName"); // "Adam of Eden"
adam("getTestName"); // "unknown message: getTestName"

credits to the great @petermichaux:

https://gist.github.com/4431905

2 Responses
Add your response

Mhmm, seems your example will always return the full name.

over 1 year ago ·

oops fixed! Thanks!

over 1 year ago ·