开发者

JavaScript differences defining a function

开发者 https://www.devze.com 2023-03-08 08:54 出处:网络
I just bought the newest version of \"JavaScript: The Definitive Guide\" and already have a qu开发者_Go百科estion. :D

I just bought the newest version of "JavaScript: The Definitive Guide" and already have a qu开发者_Go百科estion. :D

Are the following lines semantically the same:

var square = function(n){
                 return n * n;
             };

and

function square(n){
    return n * n;
}

If yes, what are the advantages/disadvantages of using either of them?

Thanks for your help!


Check this out:

a(); // prints 'A'

function a(){

    console.log('A');

};

and this:

b(); // throws error. b is not a function

var b = function() {

    console.log('B');

};

Did you notice the difference?


Yes, they do the exact same thing.

The main advantage of the first approach is that it gives you a reference to that function so that you could pass it to another function or attach it to an object if you need to.


Difference is that in the first solution, you can do that :

var square = function(n){
                 return n * n;
             };

// some code

square = function(n) { return n*n*n; }

you have reference to a function. On the other solution, the function is statically declared.

Disclaimer: need JS guru to tell me if I'm wrong =).

0

精彩评论

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