Adding custom properties to a function

后端 未结 10 809
独厮守ぢ
独厮守ぢ 2020-11-27 10:34

Searching for appropriate answer proved difficult because of the existence of many other problems related to my keywords, so I\'ll ask this here.

As we know, functio

10条回答
  •  天命终不由人
    2020-11-27 11:13

    Attaching properties to functions is a beautiful (arguably sluggish/hack-ish) way of overloading the () operator, which in turn is usually used to implement functors: Object types that have one really important job, and all its other functionality (if there is any) is just a bunch of helpers. You could also interpret these functors as, basically, a "stateful" function where the state is public (most inline functions for example, have private state, that is state from the local scope).

    This JSFiddle demonstrates how we can use a function with custom properties for a translator function with additional utilities:

    /**
     * Creates a new translator function with some utility methods attached to it.
     */
    var createTranslator = function(dict) {
        var translator = function(word) {
            return dict[word];
        };
    
        translator.isWordDefined = function(word) {
            return dict.hasOwnProperty(word);
        };
    
        // Add more utilities to translator here...
    
        return translator;
    };
    
    
    // create dictionary
    var en2deDictionary = {
        'banana': 'Banane',
        'apple': 'Apfel'
    };
    
    // simple use case:
    var translator = createTranslator(en2deDictionary);
    var pre = $('
    ');
    $("body").append(pre);
    
    pre.append(translator('banana') + '\n');
    pre.append(translator('apple') + '\n');
    pre.append(translator.isWordDefined('w00t') + '\n');
    

    As you can see, this is perfect for a translator whose sole purpose is to translate. Of course there are many more examples of theses types of objects, but they are by far not as common as types with diversified functionality, such as the classic User, Animal Car etc. types. To those sort of types, you only want to add custom properties in very few cases. Usually, you want to define those as more complete classes, and have their public properties reachable through this and it's prototype.

提交回复
热议问题