tlama
tlama

Reputation: 617

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";

Upvotes: 0

Views: 131

Answers (2)

Cody
Cody

Reputation: 10015

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

Upvotes: 0

dandavis
dandavis

Reputation: 16726

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

Upvotes: 1

Related Questions