Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Storing function in object - bad practice? [closed]

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?

like image 375
Zar Avatar asked Jan 17 '12 22:01

Zar


People also ask

Can you store a function in an object JavaScript?

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.

How do you put a function into an object?

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.

Can I store a function in a variable JavaScript?

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.


1 Answers

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.

like image 162
Darin Dimitrov Avatar answered Sep 20 '22 10:09

Darin Dimitrov