2

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.

asked Sep 18, 2011 at 1:01
0

3 Answers 3

5
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).

answered Sep 18, 2011 at 1:05
Sign up to request clarification or add additional context in comments.

Comments

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

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

answered Sep 18, 2011 at 1:04

Comments

1

Pretty vague, but here you go:

var obj = {};
obj.foo = function() {
 return "baz";
};
// code...
obj.foo();
answered Sep 18, 2011 at 1:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.