开发者

Creating a function in JS [duplicate]

开发者 https://www.devze.com 2023-02-27 14:16 出处:网络
This question already has answers here: 开发者_运维知识库 Closed 11 years ago. Possible Duplicate:
This question already has answers here: 开发者_运维知识库 Closed 11 years ago.

Possible Duplicate:

Javascript: var functionName = function() {} vs function functionName() {}

I am curious to which is best pratice when creating a function in js

function x() {
    ...
}

OR

var x = function() {
    ...
}

Is there a difference or are they the exact same thing.


x(); // I work
function x() {
    ...
}
y(); // I fail
var y = function() {
    ...
}

The first is a function declaration. You can use functions before you've declared them.

The second is a assigning a function to a variable. This means you can assign to anything.

You can assing it to foo[0] or foo.bar.baz or foo.get("baz")[0]


I prefer the first form because it gets defined before variables are defined.

So, you could invoke x in a later scope because the interpreter already defined that function even though it may be declared later on in your code.

This will be simpler with some code:

x(); //logs "hi"

//...
function x() { 
   console.log("hi"); 
}

vs

x(); //fails

var x = function() { 
   console.log("hi");
};


They are not exactly the same thing, people have mentioned the forward-lookahead difference, here's a less known subtlety - the function name property:

function x(){}
x.name; // "x"

var x = function(){};
x.name; // ""


In the second case, you can pass functions as parameters and store them in arrays


You might find this useful: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope


The first is a function declaration, the latter is a function expression. Read more here while I try to find a very in-depth article I once read on the differences and implications.

Edit: Ah, here we go. Grab a cup of tea and settle in for an in-depth discussion.

0

精彩评论

暂无评论...
验证码 换一张
取 消