Lon*_*ner 7 javascript strict use-strict ecmascript-5
这是我的代码似乎表明答案是肯定的 - http://jsfiddle.net/4nKqu/
var Foo = function() {
'use strict'
return {
foo: function() {
a = 10
alert('a = ' + a)
}
}
}()
try {
Foo.foo()
} catch (e) {
alert(e)
}
Run Code Online (Sandbox Code Playgroud)
您能否引用标准中的陈述,阐明该陈述'use strict'是否自动应用于我们应用的函数中定义的所有闭包和函数'use strict'?
规范的相关部分:
http://www.ecma-international.org/ecma-262/5.1/#sec-10.1.1
其中说:
Run Code Online (Sandbox Code Playgroud)Code is interpreted as strict mode code in the following situations:
全局代码是严格的全局代码,如果它以包含使用严格指令的指令序言开头(见14.1).
如果Eval代码以包含Use Strict Directive的Directive Prologue开头,或者对eval的调用是对严格模式代码中包含的eval函数的直接调用(参见15.1.2.1.1),则Eval代码是严格的eval代码.
作为FunctionDeclaration,FunctionExpression或访问者PropertyAssignment的一部分的函数代码是严格的函数代码,如果其FunctionDeclaration,FunctionExpression或PropertyAssignment包含在严格模式代码中,或者函数代码以包含Use Strict Directive的Directive Prologue开头.
作为内置Function构造函数的最后一个参数提供的函数代码是严格的函数代码,如果最后一个参数是一个String,当作为FunctionBody处理时,它以包含Use Strict指令的Directive Prologue开头.
因此,对于在'strict scope'中明确定义的函数,它们将继承严格模式:
function doSomethingStrict(){
"use strict";
// in strict mode
function innerStrict() {
// also in strict mode
}
}
Run Code Online (Sandbox Code Playgroud)
但是使用Function构造函数创建的函数不会从其上下文继承严格模式,因此"use strict";如果您希望它们处于严格模式,则必须具有显式语句.例如,注意这eval是严格模式下的保留关键字(但不在严格模式之外):
"use strict";
var doSomething = new Function("var eval = 'hello'; console.log(eval);");
doSomething(); // this is ok since doSomething doesn't inherit strict mode
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1073 次 |
| 最近记录: |