Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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.
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).
doSomething
Add a comment
var myFunc = function() { ... }; var myObj = { func: myFunc }; myObj.func();
You can also skip the myFunc temporary variable if you want to.
myFunc
Pretty vague, but here you go:
var obj = {}; obj.foo = function() { return "baz"; }; // code... obj.foo();
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.
Explore related questions
See similar questions with these tags.