简体   繁体   English

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

[英]Difference between function expression in global scope and function declaration

I'm puzzled by something in my js. 我对我的js感到困惑。 Normally I define functions like this: 通常我定义这样的函数:

function f(){
    // do stuff
}

but I can also define functions like this: 但我也可以定义如下函数:

f = function(){
    // do stuff
}

I always thought there is no difference between them, but I now found that this is working: 我一直以为它们之间没有区别,但是现在我发现这是可行的:

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

but when I define f as follows: 但是当我如下定义f时:

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

and I click on the row, it gives a ReferenceError: f is not defined . 然后单击该行,它给出了ReferenceError: f is not defined

So I wonder: what is actually the difference between function f(){} and f = function(){} ? 因此,我想知道: function f(){}f = function(){}之间到底有什么区别?

When you define a function without using var statement, by default the function will be defined as a property in the global scope. 在不使用var语句的情况下定义函数时,默认情况下,该函数将被定义为全局范围内的属性。

Quoting MDN documentation on var , 引用有关var MDN文档

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 (eg 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. ECMAScript 5严格模式下 ,分配给未声明的变量将引发错误。

So, when you define with function function_name(...){...} syntax, it will be in the current scope. 因此,当您使用function function_name(...){...}语法进行定义时,它将位于当前范围内。

Since the second function definition is in the global scope tr 's onclick can find f . 由于第二个函数定义在全局范围内,因此tr的onclick可以找到f Try using var statement like this 尝试像这样使用var语句

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

you will get the same ReferenceError: f is not defined . 您将得到相同的ReferenceError: f is not defined

You forgot the var statement. 您忘记了var语句。 The function is defined globally when using f = function(){ } . 使用f = function(){ }时会全局定义该函数。 This is why it's accessible from the onclick handler and the other is not. 这就是为什么可以从onclick处理程序访问它,而另一个不能访问的原因。

Please also read var functionName = function() {} vs function functionName() {} as suggested by @Nehal. 也请阅读@Nehal建议的var functionName = function(){}与function functionName(){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM