在严格模式下,只能在顶层声明函数 [英] Functions may be declared only at top level in strict mode

查看:53
本文介绍了在严格模式下,只能在顶层声明函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this error when using FireFox with strict mode. But am unsure what it means. I assumed it meant that the function had to be declared before it was called upon but the error still occurs.

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

SyntaxError: in strict mode code, functions may be declared only at top level or immediately within another function

这是我引起错误的代码段:

This is my snippet of code where it is causing the error:

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正确地写出这段代码?顶层是什么意思?这是否意味着在函数中是全局定义的而不是局部的?

So i'm wondering how would I write this snippet of code out correctly with strict ? What does it mean by top level ? Does that mean globally defined and not locally within a function ?

还考虑到我已经使用严格为什么在Chrome中不会出现此问题?

Also given I have use strict why does this problem not occur in Chrome?

推荐答案

在严格模式下,必须在父函数内的其他代码之前放置局部函数:

You must put local functions BEFORE other code within the parent function in strict mode:

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

在本文中对此进行了描述:

This is described in this articles:

MDN严格模式

尽管在我自己的测试中(并且与我读过的文章相反),我发现当前版本的Chrome和Firefox仅抱怨本地函数定义是否在块内(例如在内).if for 语句或类似的块.

In my own testing though (and counter to the articles I've read), I find that current versions of both Chrome and Firefox only complain about a local function definition if it is inside a block (like inside an if or for statement or a similar block.

我想我需要去找到一个实际的规格,看看上面说的是什么.

I guess I need to go find an actual spec to see what is says.

这篇关于在严格模式下,只能在顶层声明函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆