Is it considered bad coding-practice to store functions in an object instead of just defining them (and therefore globally)?
Consider:
1.
Foo = { bar: function() { alert("baz"); } }
Foo.bar();
vs.
2.
function bar() { alert("baz"); }
bar();
Sure, it might be slightly less code for the second example, but when you start to get lots of functions - it will get messy. I find it way, way, cleaner to, for example, use Game.update()
instead of using updateGame(); or similar. When getting deeper, like Game.notify.admin(id)
and so on, it gives you even prettier code.
Is there any downsides by storing a function in an object?
In JavaScript, functions are called Function Objects because they are objects. Just like objects, functions have properties and methods, they can be stored in a variable or an array, and be passed as arguments to other functions.
You can call a function inside an object by declaring the function as a property on the object and invoking it, e.g. obj. sum(2, 2) . An object's property can point to a function, just like it can point to a string, number or other values.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
The first approach is preferred. This way you are explicitly defining the scope of your functions instead of polluting the global scope. There are no downsides of using the first approach. Only upsides :-)
Conclusion: always use the first approach to define functions. The second is like javascript in the 90s, let's leave it rest in peace back in the past and use proper scoping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With