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

时间:2013-10-09 20:50:02

标签: javascript

我有以下代码,我希望在对象文字中直接定义函数( server )上的属性( server )( actions < / em>的)。

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

2 个答案:

答案 0 :(得分:1)

在有疑问时使用函数,或者在任何时候想要使用需要变量的复杂构造时使用函数:

var actions = {

    first: (function(){ 

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

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

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

答案 1 :(得分:0)

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). For instance, AngularJS has a $http module which can be used like $http({...}) or $http.get(...) -- this is because its a decorated function.

Cheers