Search code examples
javascriptobject-literalfunction-attributes

Create a function-attribute of a function, which is, in its turn, a method of an object literal


It is known, that in JS you're allowed to create a function inside function, like this:

function digit() { return 9 };
digit.five = function() { return 5 };

digit();     // 9
digit.five() // 5

I don't know whether it is a bad practice or not (probably it is) – since it works properly, you may use it.

But what if we had a digit() function as a method of some object (see the example below)?
Then how would we declare digit.five()? Assumed, that we want to declare it in scope of obj.

var obj = {
    digit: function() { return 9 },
 // digit.five: … ???
 // digit["five"]: … ???
}

obj.digit();     // 9
obj.digit.five() // 5

Is it possible at all without creating new obj.digitFive() method?


P.S: User nnnnnn here says, that we could create an attribute inside obj.digit():

var obj = {
    digit: function () {
        return 9;
        obj.digit.five = function () { return 5 };
    }
}

Is this the only way to do that?


Solution

  • There’s no built-in syntax to put properties on function expressions, no. You can add the property afterwards:

    var obj = {
        digit: function() { return 9 },
    };
    
    obj.digit.five = function() { return 5 };
    

    ES6’s standard function Object.assign works well too:

    var obj = {
        digit: Object.assign(
            function() { return 9 },
            { five: function() { return 5 } }
        ),
    };