2013-01-20 47 views
1

this articleJavaScript中的「嚴格使用」不起作用?

Adding 「use strict」 as the first statement¹ in your JavaScript code will enforce Strict Mode over the entire

那麼爲什麼:

"use strict"; 
012; 

不會引發錯誤

(function() { 
    "use strict"; 
    012; })(); 

呢? (八進制文字不是在嚴格模式允許的。)

John resig says nothing about it. he just says :

Simple. Toss this at the top of a program to enable it for the whole script:

"use strict"; Or place it within a function to turn on strict mode only within that context.

function imStrict(){ "use strict"; // ... your code ... }

編輯:

enter image description here

編輯#2。

我在控制檯中測試了代碼(chrome)。在jsbin示例中 - 它正在工作。仍然,我不明白爲什麼它在控制檯中表現不同。

+0

如果你用'strict strict'會發生什麼; 012;'在一行? – melpomene

+0

@melpomene相同。剛剛測試過。 –

+1

那麼,無論你使用的是什麼,REPL都不支持頂級的「use strict」。 – melpomene

回答

1

確實拋出一個錯誤。

[email protected]:~ # cat > tmp/foo.js 
"use strict"; 
012; 

[email protected]:~ # node tmp/foo.js 

/users/quentin/tmp/foo.js:2 
012; 
^^^ 

module.js:434 
    var compiledWrapper = runInThisContext(wrapper, filename, true); 
         ^
SyntaxError: Octal literals are not allowed in strict mode. 
    at Module._compile (module.js:434:25) 
    at Object..js (module.js:464:10) 
    at Module.load (module.js:353:31) 
    at Function._load (module.js:311:12) 
    at Array.0 (module.js:484:10) 
    at EventEmitter._tickCallback (node.js:190:38) 
+1

沒有它不會看到我的編輯請。 –

+0

@RoyiNamir - 因此,無論有什麼奇怪的你正在執行它,或者有沒有錯誤的地方,問題是你的工具 – Quentin

+0

的工具是鉻 –

1

控制檯不行爲相同的方式爲其他地方,嘗試打開在瀏覽器下面,你會看到,而不需要將其包裝在一個函數的錯誤再次出現。

<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8" /> 
     <title>use strict</title> 
     <script> 
"use strict"; 
012; 
     </script> 
    </head> 
    <body> 
    </body> 
</html> 

你可以告訴控制檯通過鍵入剛~+等不同的方式實現直接執行(你會得到一個SyntaxError: Unexpected token })。
有可能通過寫這樣的代碼直接複製類似的行爲(我不會把它相同因爲我不知道該控制檯是怎麼做的那樣)

example: { // labeled block 
    "use strict"; // your code 
    012; 
} // end of block, no SyntaxError thrown for strict 
+0

我認爲它應該提供相同的結果。 –

+0

這種假設是錯誤的,嘗試一下,看看會發生什麼。 –

+0

看到我的編輯#2。生病是很高興得到一個樣本,其控制檯的犯規行爲像正常流動的代碼。(除非這個樣本)。 –

-1

012是一個八進制它在嚴格模式下是不允許的,因爲它在ECMA-262第3版中已被棄用。爲了向後兼容,JavaScript 1.5仍支持八進制整數字面值。你的例子會拋出一個錯誤!

你有3種可能性。

  1. 刪除的八進制

  2. 不使用嚴格的模式

  3. ,或者您可以使用八進制第一和包裝所有的代碼在一個匿名函數和限制嚴格的模式您立即調用函數表達式(iife):

012;

(function() { 
    "use strict"; 

    ... your code 
})(); 
+1

問題是「*如何拋出一個嚴格的代碼錯誤(與八進制作爲示範)用程序級'」使用嚴格的「'(控制檯演示)*?」你的回答是沒有關係的那 – Bergi

+0

不,不是問題。問題是,爲什麼給定的例子不是拋出一個錯誤(但它是!)。 – hereandnow78