1
var api = {};

api.c = function () {return 1};
api.c.m = function () {return 2};

alert(api.c()); // returns 1
alert(api.c.m()); // returns 2

var api2 = {
    c: function () {}; // can't put m inside c in object literal notation
};

How would we embed m in c in object literal notation?

2

2 Answers 2

5

You can't. However, you could do

Object.defineProperty(api.c, 'm', { value: function() { return 2; } });

Since Object.defineProperty returns the object, you could do

var api = {
    c: Object.defineProperty(function() { }, 'm', {
        value: function() { return 2; }
    })
};

Or for multiple properties:

var api = {
    c: Object.defineProperties(function() { }, {
        m: { value: function() { return 2; } },
        ...
    })
};

This may come closest to satisfying your desire to write the function properties in object literal form.

Or, you could use the extend feature available in most frameworks (or Object.assign in ES6):

var api = {
    c: Object.assign(function() { }, {
        m: function() { return 2; }
    )
};

Feel free to replace Object.assign with $.extend, _.extend, etc.

Depending on your tolerance for ugliness, you might try the following, a variation on @zerkms's proposal without the IIFE (you'll need a variable x):

var api = {
    c: (x = function() { }, x.m = function() { return 2; }, x)
};
Sign up to request clarification or add additional context in comments.

1 Comment

really nice... Will be withholding the answer until later.
2

It technically is possible, but it's ugly

var api2 = {
    c: (function() {
        var f = function() {};
        f.m = 'something else';

        return f;
    }())
};

So I personally don't see a good reason to do it that way instead of how you do it in the 1st case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.