简体   繁体   中英

Setting properties on functions in JavaScript object literal notation

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?

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)
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM