문제

In Javascript what is the difference between:

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

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

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

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top