I’ve read that rather than simply writing a bunch of functions, I should use an object literal.
What are the advantages of object literal, with examples?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As Russ Cam said, you avoid polluting the global namespace, which is very important in these days of combining scripts from multiple locations (TinyMCE, etc.).
As Alex Sexton said, it makes for good code organisation as well.
If you’re using this technique, I’d suggest using the module pattern. This still uses object literals, but as the return value from a scoping function:
External use:
The scoping function is wrapped around all of your functions, and then you call it immediately and store its return value. Advantages:
{name: function() { ... }}format, all of your functions are anonymous, even though the properties referencing them have names.) Names help tools help you, from showing call stacks in a debugger, to telling you what function threw an exception. (2015 Update: The latest JavaScript specification, ECMAScript 6th edition, defines a large number of ways the JavaScript engine must infer a function’s name. One of those is when the function is assigned to a property as in our{name: function() { ... }}example. So as engines implement ES6, this reason will go away.)internalSomethingabove). No other code on the page can call those functions; they’re truly private. Only the ones you export at the end, in the return statement, are visible outside the scoping function.Example of returning different functions: