【问题标题】:which is the better way of defining a function? [duplicate]定义函数的更好方法是什么? [复制]
【发布时间】:2013-06-09 18:09:00
【问题描述】:

它们之间有什么区别吗? 这两种方法我都用过,但不知道哪一种效果更好,哪一种更好?

function abc(){

    // Code comes here.
}

abc = function (){

    // Code comes here.
}

定义这些函数有什么区别吗? i++ 和 ++i 之类的东西?

【问题讨论】:

  • 为什么又添加了html标签?这个问题与HTML无关!
  • 那是因为人们可能会将这个问题视为 java 的问题——它使用面向对象的方法......
  • 该问题已标记为javascript。很明显,它与 Java 无关。如果有人不知道 JavaScript 和 Java 之间存在差异,那么他们就不应该编程。
  • 好吧!!我现在应该删除它吗??

标签: javascript function user-defined-functions definition hoisting


【解决方案1】:
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/

【讨论】:

  • Nitpick: "那么abc 还没有声明,不能使用。" 变量声明也被提升了,所以声明了变量,但是它还没有值.
  • @FelixKling - 已更新。干杯。
【解决方案2】:

简短回答:无。

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

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

(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
    };
})();

【讨论】:

    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多