这是定义函数更好的方法

which is the better way of defining a function?

本文关键字:方法 更好 函数 定义      更新时间:2023-09-26

两者有什么区别吗?我一直在使用这两种方式,但不知道哪一个做什么,哪一个更好?

function abc(){
    // Code comes here.
}
abc = function (){
    // Code comes here.
}

定义这些函数有什么区别吗?比如i++和++i ?

function abc(){
    // Code comes here.
}

将被吊装。

abc = function (){
    // Code comes here.
}

不能吊装。

例如:

 abc(); 
 function abc() { }

abc被提升到封闭作用域的顶部时,代码将运行。

如果你这样做了:

  abc();
  var abc = function() { }

abc已声明,但没有值,因此不能使用。

关于哪个更好更多的是关于编程风格的争论。

http://www.sitepoint.com/back-to-basics-javascript-hoisting/

简短回答:none

将函数放在全局命名空间中。任何人都可以访问它,任何人都可以覆盖它。

标准的更安全的方法是将所有内容包装在一个自调用函数中:

(function(){
    // put some variables, flags, constants, whatever here.
    var myVar = "one";
    // make your functions somewhere here
    var a = function(){
        // Do some stuff here
        // You can access your variables here, and they are somehow "private"
        myVar = "two";
    };

    var b = function() {
        alert('hi');
    };
    // You can make b public by doing this
    return {
        publicB: b
    };
})();