函数只能在严格模式下在顶级声明

Functions may be declared only at top level in strict mode

本文关键字:声明 模式 函数      更新时间:2023-09-26

在严格模式下使用FireFox时出现此错误。但我不确定这意味着什么。我认为这意味着在调用函数之前必须声明它,但错误仍然会发生。

SyntaxError:在严格模式代码中,函数只能在顶级或立即在另一个函数中声明

这是我的代码片段,它导致了错误:

var process = new function(){
  var self = this;
  self.test = function(value,callback){
    var startTime = Date.now();
     function update(){     //<--- error is here
                value++;
                startTime        = Date.now();
                if(value < 100){ 
                    setTimeout(update, 0);
                }
                callback(value);
    }       
    update();
  }
};

所以我想知道如何用strict正确地写出这段代码?顶级是什么意思?这是否意味着在一个函数中全局定义而非局部定义?

同样考虑到我有use strict,为什么Chrome中没有出现这个问题?

在严格模式下,您必须将本地函数放在父函数中的其他代码之前:

var process = function () {
    var self = this;
    self.test = function (value, callback) {
        function update() {
            value++;
            startTime = Date.now();
            if (value < 100) {
                setTimeout(update, 0);
            }
            callback(value);
        }
        var startTime = Date.now();
        update();
    }
};

这在本文中有描述:

新的ES5严格模式要求:不在程序或函数顶层的函数语句被禁止

MDN严格模式

不过,在我自己的测试中(与我读过的文章相反),我发现当前版本的Chrome和Firefox都只抱怨本地函数定义在块内(比如iffor语句或类似块内)

我想我需要去找一个实际的规格,看看上面写着什么。

Internet explorer错误明确指出函数名称不能在函数中"声明"。因此,使用自调用函数表达式对我来说很有效

此代码失败:

    c.prototype.isitReal=function(t){
    var matched = false;
    this.each(function(item){
        // declaring a new function within a function fails 
        function getChildren(el){
            ....
            getChildren(el[a].children);
            ....
        }
        getChildren(el.children); // invoke function
    });
    return matched;
};

此代码有效:

    c.prototype.isitReal=function(t){
    var matched = false;
    this.each(function(item){
        // convert the function to an expression of a function
        // by wraping the entire function in ( )
        (function getChildren(el){
            ....
            getChildren(el[a].children);
            ....
            // then invoke the function expresion by adding ()
            // to the end. Pass in any arguments here also
        })(el.children,arg2,arg3);
    });
    return matched;
};

在FF 76、MSIE 10、Chrome Canary 81 中测试