javascript - 全局作用域中的函数表达式与函数声明的区别

标签 javascript function syntax

我对我的 js 中的某些东西感到困惑。通常我这样定义函数:

function f(){
    // do stuff
}

但我也可以这样定义函数:

f = function(){
    // do stuff
}

我一直认为它们之间没有区别,但我现在发现这是可行的:

f = function(){
    alert('IT WORKS!!');
}

function createCallback(request){
    request.done(function(data){
        var html = '';
        data['result'].forEach(function(bill){
            html += "<tr onclick=\"f();\"><td>" + bill.title + "</td></tr>";
        });
        $("#someId").html(html);
    });
}

但是当我如下定义f时:

function f(){
    alert('IT WORKS!!');
}

然后我点击该行,它给出了一个ReferenceError: f is not defined

所以我想知道:function f(){}f = function(){} 之间究竟有什么区别?

最佳答案

当您在不使用 var 语句的情况下定义一个函数时,默认情况下该函数将被定义为全局范围内的一个属性。

引用 MDN documentation on var ,

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are:

  1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global.

  2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed.

  3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted).

Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus it is recommended to always declare variables, regardless of whether they are in a function or global scope. And in ECMAScript 5 strict mode, assigning to an undeclared variable throws an error.

因此,当您使用 function function_name(...){...} 语法定义时,它将在当前范围内。

由于第二个函数定义在全局范围tr的onclick可以找到f。尝试像这样使用 var 语句

var f = function(){
    alert('IT WORKS!!');
}

你会得到同样的ReferenceError: f is not defined

关于javascript - 全局作用域中的函数表达式与函数声明的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28125202/

相关文章:

javascript - 关闭鼠标悬停时打开的弹出菜单时防止恢复焦点

javascript - JSON从所有网站的所有列表中动态获取两个公告

angular - 父子组件如何通过点击事件进行通信

c - BMI 计算器实验室找不到问题

bash - 带变量的括号扩展?

c++ - 如何在 C/C++ 中描述指向数组的 const 指针?

syntax - java代码中的Scala : $colon

javascript - 解构 API https ://randomuser. me/api/以获取 API 返回的用户个人资料的标题、姓氏和名字大照片

javascript - 检测用户是否单击了弹出窗口中的元素

Javascript - 为什么下面的函数定义出错?