JavaScript ad style

In Javascript, I saw three different ways to define a function.

  • Regular style:

function foo() { //do something }

  • New Js Ninja Style

var foo = function(){ //do something }

  • DOM specific style

window.foo = function(){ //do something }

What question,

What is the difference between the three previous ones? And which one should I use and why?

+4
source share
2 answers

The first is a function declaration. It rises (you can use it anywhere inside the current volume).

The second option is to define a variable using an anonymous function. The variable rises, the destination remains in place. The function cannot be used before the line where you assigned it.

The third one assigns a global method. Like the second, although it works with a global object, which is not very good.

However, you might think of a fourth alternative (named functional expression):

 var foo = function bar(){ //do something } 

Here, the bar will be accessible only within itself, which is useful for recursion, and not for changing the current area.

You choose any approach based on your needs. I would vote against the second approach, as it behaves like a variable.

As soon as you indicate both the second and the third options, I would like to recall that a polluting global object is considered bad practice . You better think about using spontaneous anonymous functions to create a separate area, for example.

 (function(){ var t = 42; // window.t still does not exist after that })(); 

I suppose you can find a more detailed article on JavaScript Scoping and Hoisting .

+10
source

First, see Javascript: var functionName = function () {} vs function functionName () {} .

Then we get the difference between var foo = and window.foo = .

The first is a local-scope variable that is good and beautiful (if it is not done in a global area). The second is an explicit global one that has all the usual problems of global variables (for example, the likelihood of conflict with other code).

+2
source

All Articles