简体   繁体   English

以JavaScript对象文字表示法设置函数的属性

[英]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? 我们如何在对象文字符号中将m嵌入c中?

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 由于Object.defineProperty返回对象,因此您可以执行

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): 或者,您可以使用大多数框架中可用的extend功能(或ES6中的Object.assign ):

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

Feel free to replace Object.assign with $.extend , _.extend , etc. 随意用$.extend_.extend . _.extend等替换Object.assign

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 ): 根据您对丑陋的容忍度,您可以尝试以下操作,对@zerkms的建议进行变体而不使用IIFE(您需要一个变量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. 因此,我个人认为这样做的理由不是您在第一种情况下的做法,而是一个很好的理由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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