javascript 行为 - 函数表达式与函数声明 - 区别

标签 javascript

为什么没有为函数 f 创建引用

if ( function f() { } ) {
    console.log( typeof f );
}
// result: undefined 

分配/设置 变量在 if( ) 中工作正常

if ( f = 'assigned' ) {
     console.log( typeof f );
}
// result: string

我需要知道第一种情况发生了什么,因为第二种情况按预期工作

有人能解释一下吗?

最佳答案

由于您已将 function f() { } 放在表达式上下文中,因此它是一个命名函数表达式,而不是一个函数声明

这意味着当它创建一个函数,并且该函数的名称为 f 时,它会在函数(本身) 而不是在创建函数的范围内

// Global scope
function a() {
// a is a function declaration and creates a variable called a to which the function is assigned in the scope (global) that the declaration appears in
    function b() {
    // b is a function declaration and creates a variable called a to which the function is assigned in the scope (function a) that the declaration appears in
    }
    var c = function d() {
    // c is a variable in the scope of the function b. The function d is assigned to it explicitly
    // d is a function expression and creates a variable called d to which the function is assigned in the scope (function d) of itself

    };
}

关于javascript 行为 - 函数表达式与函数声明 - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49543214/

相关文章:

javascript - jsp页面只显示视频缩略图

javascript - 浏览器加载损坏的旧 Javascript

javascript - 跨域ajax请求

php - 使用 JS setTimeout 在循环中发布 AJAX 请求,但 setTimeout 被调用得太频繁了

javascript - 将文件名和文件类型放在一个数组中

javascript - 导航菜单指示器 - 在悬停、单击和滚动时滑动

javascript - Node.js 导出函数错误

javascript - jQuery 语句中的三元运算符

javascript - 使用dojo触发窗口调整大小事件

javascript - 从被调用函数的位置获取父元素