函数只能在严格模式下在顶级声明
Functions may be declared only at top level in strict mode
在严格模式下使用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都只抱怨本地函数定义在块内(比如if
或for
语句或类似块内)
我想我需要去找一个实际的规格,看看上面写着什么。
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 中测试
相关文章:
- Dojo不解析自定义小部件的模板html中的小部件声明性
- Javascript,访问一个主要对象模块模式中的每个对象
- 是否有任何snippet或jQuery插件可以列出easylist.txt模式匹配的DOM中的所有元素
- 试图在引导模式内动态生成图表,得到offsetWidth错误
- 直接在函数声明上使用function.prototype.bind
- 同位素库错误:未捕获错误无布局模式包装生产线8
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 未知的 JavaScript 函数声明模式
- SyntaxError:严格模式不允许在词法嵌套语句中声明函数
- 这种减少if语句中声明的变量范围的模式是一种好的做法吗
- “函数声明不能嵌套在语句中” - IE 处于严格模式错误
- 使用在另一个服务方法中声明为模块模式的服务方法之一
- AngularJS中是否存在一致声明$scope变量的模式
- 什么'声明和获取js对象的最佳方式是什么?(模式)
- 函数只能在严格模式下在顶级声明
- AngularJS:块作用域声明(let、const、function、class)在严格模式之外还不支持
- 未捕获的SyntaxError:在严格模式之外还不支持块范围的声明(let、const、function、class)
- 未捕获的SyntaxError:在严格模式代码中,函数只能在顶层或立即在另一个函数中声明
- 模块模式中的函数声明与函数表达式
- jQuery+Module模式:何时声明/查询元素