I was wondering whether there is any performance / advantage of writing javascript in this format ?
var myFuncs = {
var firstFun = function() {
// do something
},
var secondFunc = function() {
// do something
},
var thirdFunc = function() {
// do something
}
}
So they can be called like
myFuncs.firstFun();
I’m trying to understand how this is more advantageous [other than code readability] ?
Function vs Object declaration
You can’t use that particular syntax, the correct form is:
The advantage to writing functions within an object has to do with namespacing and context. If you wrote:
the function would be defined at
window.firstFn. Adding the functions onmyFuncsmakes the functions accessible atwindow.myFuncs.firstFn. If you want your JavaScript to work with other scripts you wouldn’t want to have yourfoofunction conflict with someone elsesfoofunction:The calling context (
this) of the function will also be different:Closure Syntax
What you may be getting confused with is the syntax for declaring functions within a closure:
In this case the closure is used to prevent the function from polluting the global scope (
window.foowill not be set). This allows multiple scripts to use the same function names without worrying about being overridden.OOP Syntax
The object syntax is often used to define the prototype for a JavaScript “constructor”. In JS all functions can be called as a constructor simply by using the
newkeyword when the function is called:For readability/maintainability/consistency you should always name your constructor using PascalCase:
Without getting too lost in the details of how prototype works, you can assign methods to be shared across every instantiated object of a function by assigning an object to the function’s
prototypeproperty: