最近,我通过Crockford的JSLint运行了一些我的JavaScript代码,它给出了以下错误:
第1行问题1:缺少"使用严格"声明.
做一些搜索,我意识到有些人会加入"use strict";他们的JavaScript代码.一旦我添加了语句,错误就会停止显示.不幸的是,谷歌没有透露这个字符串声明背后的历史.当然它必须与浏览器如何解释JavaScript有关,但我不知道效果会是什么.
那么它是"use strict";什么,它意味着什么,它是否仍然相关?
当前的任何浏览器都会响应"use strict";字符串还是将来使用?
我试图通过阅读原始规范来围绕ES6中新的标准化块级功能.我的肤浅理解是:
然而,由于这些语义的一部分被指定为"可选的"并且仅对于Web浏览器是必需的(附件B),因此这进一步复杂化.所以我想填写下表:
| Visible outside of block? | Hoisted? Up to which point? | "TDZ"? |
------------------------------------------------------------------------------------------------------------------------
| Non-strict mode, no "web extensions" | | | |
| Strict mode, no "web extensions" | | | |
| Non strict mode, with "web extensions | | | |
| Strict mode, with "web extensions" | | | |
另外我不清楚在这种情况下"严格模式"是什么意思.这种区别似乎在附件B3.3中引入,作为函数声明的运行时执行的一些附加步骤的一部分:
1. If strict is false, then
...
Run Code Online (Sandbox Code Playgroud)
但是,据我所知,strict指[[Strict]]的是函数对象的内部插槽.这是否意味着:
// Non-strict …Run Code Online (Sandbox Code Playgroud) 第一类函数是否意味着它们表现为变量?显然,它们的行为与变量完全不同,因为:
console.log(foo);
var foo = 'bar';
Run Code Online (Sandbox Code Playgroud)
......不起作用,而这个:
console.log(foo());
function foo() {
return('bar');
}
Run Code Online (Sandbox Code Playgroud)
...一样.
那说,这个:
console.log(foo());
var foo = function() { return 'bar'; };
Run Code Online (Sandbox Code Playgroud)
不起作用,这更加一致.
是什么赋予了?
javascript syntax functional-programming first-class-functions
var foo = function(){ return 1; };
if (true) {
function foo(){ return 2; }
}
foo(); // 1 in Chrome // 2 in FF
//I just want to be sure, is FF 4 not "standard" in this case?
Run Code Online (Sandbox Code Playgroud)
编辑:
如果我们有这个:
var foo = function(){ return 1; };
if (true) function foo(){ return 2; }
foo(); // is 1 standard or is 2 standard?
Run Code Online (Sandbox Code Playgroud) foo();
if (true) {
function foo() {
console.log(1);
}
} else {
function foo() {
console.log(2)
}
}Run Code Online (Sandbox Code Playgroud)
在chrome中它显示Uncaught TypeError,但在Safari中它显示2.
console.log(a());
function a(){
console.log("hello");
}
Run Code Online (Sandbox Code Playgroud)
从上面的代码,我希望"hello"(和一些undefineds)在控制台上登录.但是萤火虫给了
ReferenceError: a is not defined
Run Code Online (Sandbox Code Playgroud)
萤火虫不起吊?
请考虑以下代码:
function A() {
console.log("first");
}
var f = A;
function A() {
console.log("second");
}
var g = A;
f();
g();
Run Code Online (Sandbox Code Playgroud)
它在萤火虫中输出"第一","第二",这是我认为它应该做的.
但它在Chrome控制台或firefox中输出"秒","秒",(从文件执行时,而不是在firebug中).
为什么要改变'f'中的参考值?我做第二个"函数A(){"??
看起来好像是吊装是问题(请参阅apsillers的回答).但是,为什么这个例子正常工作(我的意思是输出第一秒):
var A = function A() {
console.log("first");
}
var f = A;
A = function A() {
console.log("second");
}
var g = A;
f();
g();
Run Code Online (Sandbox Code Playgroud)
我在第二个函数声明中使用"A = ..."的事实阻止了这个函数的提升?
javascript ×7
syntax ×2
ecmascript-6 ×1
firebug ×1
firefox ×1
hoisting ×1
jslint ×1
standards ×1
use-strict ×1