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
SmRndGuy
1,8295 gold badges32 silver badges51 bronze badges
3 Answers 3
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
Matthew Flaschen
286k53 gold badges525 silver badges554 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Comments
Pretty vague, but here you go:
var obj = {};
obj.foo = function() {
return "baz";
};
// code...
obj.foo();
answered Sep 18, 2011 at 1:34
David G
97.6k41 gold badges173 silver badges258 bronze badges
Comments
lang-js