Question

In Javascript what is the difference between:

var name = function() { //stuff to do };

{name : function() { //stuff to do } };

function name() { //stuff to do };

Était-ce utile?

La solution

As written by Stoyan Stefanov in "JavaScript Patterns":

In function declarations and named function expressions, the name property is defined. In anonymous function expressions, it depends on the implementation; it could be undefined (IE) or defined with an empty string (Firefox, WebKit):

function foo() {} // declaration
var bar = function () {}; // expression
var baz = function baz() {}; // named expression

foo.name; // "foo"
bar.name; // ""
baz.name; // "baz"

The name property is useful when debugging code in Firebug or other debuggers. When the debugger needs to show you an error in a function, it can check for the presence of the name property and use it as an indicator. The name property is also used to call the same function recursively from within itself. If you were not interested in these two cases, then an unnamed function expression would be easier and less verbose.

The case against function declarations and the reason to prefer function expressions is that the expressions highlight that functions are objects like all other objects and not some special language construct.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top