Ad

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 nnnnnnheresays, 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?

Ad

Answer

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 } }
    ),
};
Ad
source: stackoverflow.com
Ad