Functions may be declared only at top level in strict mode

后端 未结 2 1370
挽巷
挽巷 2020-12-11 07:00

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

相关标签:
2条回答
  • 2020-12-11 07:09

    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.

    0 讨论(0)
  • 2020-12-11 07:10

    The Internet explorer error explicitly states functions names cannot be "declared" within a function. So using a self-invoking function expression has worked for me.

    This code fails:

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

    This code works:

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

    Tested in FF 76, MSIE 10, Chrome Canary 81

    0 讨论(0)
提交回复
热议问题