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

854 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST 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 } }
    ),
};
0
On

Not sure if that answers your question, but you could do this:

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

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

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

Remember - in JS functions are objects :)

So in order to create obj.digit.five attribute you have to declare obj.digit attribute first (it could be anything but has to be defined object) and then you could add keys to this attribute.

The problem is if you try to create obj.digit.five without creating obj.digit first, you would get "unefined" error.

Remember that creating digit as in your first example creates anonymous function and assigns it to digit key. You could try other solution and create this function on side like:

var digit = function() {...};
digit.five = function() {...};
digit.otherproperty = 3;

And then assign all the properties/functions/etc. to it and then assign this created variable to obj like:

obj.digit = digit;