JavaScript named expressions

近期一直在看汤姆大叔写的博文,他所介绍的知识点与理论较为清晰,命名函数表达式是我之前从没有去进行深究过的原理,虽然已多次在项目中使用javascript,但基础还是不都扎实,多看多思多想是一直必须坚持的。这篇文章作为学习笔记,很多知识点都是汤姆大叔所总结的,汤姆大叔博客链接在文末。

Function declaration: function function name (parameter: optional) {function body}
function expression: function function name (optional) (parameter: optional) {function body}
If the function name is not declared, it must be an expression.
If function foo (){} is a function expression as part of an assignment expression; if fuction foo(){} is contained in a function body or at the top of the program, then it is a function declaration

function foo(){
    
    }//声明,因为是程序的一部分
var bar=function foo(){
    
    };//表达式,赋值表达式
new function bar(){
    
    };//表达式,new表达式
(function(){
    
    //表达式,()是一个分组操作符,它的内部只能包含表达式
    function bar(){
    
    }//声明,函数体的一部分
})();

Differences:
1. Function declarations will be parsed and evaluated before any expressions are parsed and evaluated. Note: Function declarations can be used in conditional statements, but different environments may have different execution results. It is best to use function expressions.
2. Function declaration can only appear in the program or function body, not in the block (if, while, for statement)
3. Function statement is not declared during variable initialization, but at runtime (with function expression The same formula). Once the identifier of a function statement is declared, it can take effect in the entire scope of the function.

// 此刻,foo还没用声明
  typeof foo; // "undefined"
  if (true) {
    // 进入这里以后,foo就被声明在整个作用域内了
    function foo(){
    
     return 1; }
  }
  else {
    // 从来不会走到这里,所以这里的foo也不会被声明
    function foo(){
    
     return 2; }
  }
  typeof foo; // "function"

Guess you like

Origin blog.csdn.net/zn740395858/article/details/70316422