2011-07-05 10 views
14

私たちのhtmlファイル(外部jsファイルをインポートする)に既に "use strict"がある場合、外部jsファイルに "use strict"を入れる必要がありますか?私たちのhtmlファイルにすでに "use strict"がある場合、外部jsファイルに "use strict"を入れる必要がありますか?

そして、我々の外部JSファイルは、「厳格な使用」を持っていない場合、彼らは「厳格な使用」はHTMLファイル内でまだ「厳しい」ですか?

例:

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script> 
     "use strict"; 
     function f() { 
      // calling File1 functions (File1 does not have "use strict"; at the top) 
      // are the File1 functions "strict"? 
     } 
    </script> 
    <script src="File1.js"></script> 
    <script> 
     //by the way.. is it strict here ? 
    </script> 
</head> 
<body> 
</body> 
</html> 
+0

なぜいけないのでしょうか?あなたは約15バイトほど心配ですか? – tjameson

+7

あなたは完全に私の質問を誤解し –

+0

ええと、私のコメントは、あなたも知っておく必要理由に精査しようとしていました。よりポータブルにするためにどこでも厳密に使用してください。 15バイトかそれはあなたを殺すつもりはないので、明快にするためにそれを使用してください。 – tjameson

答えて

20

あなたはそれらを厳密にするために各スクリプト(または関数)の先頭に"use strict";(または'use strict';)を挿入する必要があります。あなたの例では、File1.jsの関数はでなく、であり、2番目のブロックは厳密ではありません。詳細は、https://developer.mozilla.org/en/JavaScript/Strict_mode#Invoking_strict_modeを参照してください。

これが当てはまらなかった場合、それは厳密にのみ明示的に指定し、スクリプトや個々の機能に適用されることを意味しますので、strictモードを使用すると、インポートサードパーティのスクリプトを無効にすることができます。例えば

external.js

console.log("C: This script is non-strict."); 

var g = function (x) { 
    console.log("g is non-strict regardless of caller."); 
    return 2 * x; 
}; 

test.html

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script> 
     "use strict"; 
     console.log("A: This script element is strict."); 
     function f() { 
      console.log("The strictness of a script does not affect" + 
        " the strictness of external scripts, so g is" + 
        " still non-strict when called from f."); 
      return g(3); 
     } 
    </script> 
    <script src="external.js"></script> 
    <script> 
     f(); 
     console.log("B: This script element is non-strict.") 
    </script> 
</head> 
<body> 
</body> 
</html> 
+0

外部の.jsファイルに "use strict"が設定されている場合は、右のそれの一番上に、外部の.jsファイル内の関数が実行されたときにインポートするhtmlファイルには、厳格な使用を持っていない場合でも、彼らは「厳しい」ですか? –

+0

@KJelly – RobG

+0

...]リンクを読む:はい、外部JSファイルは '「厳格な使用」がある場合;'先頭に、それは関係なく、呼び出し側が厳格であるかどうかを厳密になります。 – cwb

関連する問題