zoukankan      html  css  js  c++  java
  • What is the difference between a function expression vs declaration in JavaScript?

     

     
     

    This question already has an answer here:

    What is the difference between the following lines of code?

    //Function declaration
    function foo() { return 5; }
    
    //Anonymous function expression
    var foo = function() { return 5; }
    
    //Named function expression
    var foo = function foo() { return 5; }
    

      

    • What is a named/anonymous function expression?
    • What is a declared function?
    • How do browsers deal with these constructs differently?

    They're actually really similar. How you call them is exactly the same, but the difference lies in how the browser loads them into the execution context.

    function declarations loads before any code is executed.

    While function expressions loads only when the interpreter reaches that line of code.

    So if you try to call a function expression before it's loaded, you'll get an error

    But if you call a function declaration, it'll always work. Because no code can be called until all declarations are loaded.

    ex. Function Expression

    alert(foo()); // ERROR! foo wasn't loaded yet
    var foo = function() { return 5; } 
    

      

    ex. Function Declaration

    alert(foo()); // Alerts 5. Declarations are loaded before any code can run.
    function foo() { return 5; } 
    

      

    As for the second part of your questions.

    var foo = function foo() { return 5; }
    

      

     is really the same as the other two. It's just that this line of code used to cause an error in safari, though it no longer does.

  • 相关阅读:
    (摘)Zebra打印机异常处理
    (摘)Chart Y轴设置为百分比
    关于ZFS、GPT、4K、Geom Label的一些说明
    (转)ASP.NET性能优化之分布式Session
    (转)WebService的事务处理
    SqlSever分页查询,仅扫描一次表
    (转)对.net系统架构改造的一点经验和教训
    字典树
    Ajax
    Lunix 命令
  • 原文地址:https://www.cnblogs.com/hephec/p/4589955.html
Copyright © 2011-2022 走看看