简体   繁体   English

是否可以在javascript中的对象文字上定义函数属性?

[英]Is it possible to define a function property on an object literal in javascript?

I have the following code and I would like to have the property ( server ) on function ( first ) defined directly in the object literal ( actions ). 我有以下代码,并且我希望直接在对象文字( 操作 )中定义函数( 第一个 )的属性( 服务器 )。

var actions = {
    first: function(){
        console.log("First")
    },
    second: function(){
        console.log("Second")
    },
};
actions.first.server = "server_1";

use a function when in doubt, or anytime you want to use a complex construct where a variable is expected: 在有疑问时或在任何需要使用变量的复杂结构时使用函数:

var actions = {

    first: (function(){ 

         function first(){
              console.log("First")
         }; 

         first.server="server_1"; 
         return first; 
     }()),

    second: function(){
        console.log("Second")
    }
};

FunctionDecorator 功能装饰器

Pass your function as a context to a class/decorator -- or -- add the property deliberately: 将您的函数作为上下文传递给类/装饰器-或-故意添加属性:

function FunctionDecorator(server) { this.server = server; return this; }
var object = {
    first: FunctionDecorator.call(function first() {}, 'server_1')
};

-- OR -- - 要么 -

var object = {
    first: function first() { first.server = first.server || getServer(); }
};

However, I would say you could work more on some OOP as this is somewhat cludgey unless you want callable objects (using the decorator method). 但是,我想说您可以在某些OOP上做更多的工作,因为除非您想要可调用的对象(使用decorator方法),否则这有些笨拙。 For instance, AngularJS has a $http module which can be used like $http({...}) or $http.get(...) -- this is because its a decorated function. 例如,AngularJS有一个$http模块,可以像$http({...})$http.get(...) -这是因为它具有修饰功能。

Cheers 干杯

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

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