Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

javascript - Functions may be declared only at top level in strict mode

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

};

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 ?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

New ES5 strict mode requirement: function statements not at top level of a program or function are prohibited

MDN Strict Mode

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...