SmRndGuy
SmRndGuy

Reputation: 1819

JavaScript function execution in object

I want to add a function to some object (in a form of a variable) and execute it when i need too.
How to do this?
Thanks.

Upvotes: 2

Views: 124

Answers (3)

David G
David G

Reputation: 96845

Pretty vague, but here you go:

var obj = {};
obj.foo = function() {
    return "baz";
};

// code...

obj.foo();

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 285027

obj.doSomething = function()
{
  console.log('done');
}

obj.doSomething();

This won't affect any of obj's existing fields or methods (the obvious exception being if there's already a doSomething).

Upvotes: 5

SLaks
SLaks

Reputation: 888107

var myFunc = function() { ... };
var myObj = { func: myFunc };

myObj.func();

You can also skip the myFunc temporary variable if you want to.

Upvotes: 5

Related Questions