をJavaScriptのvar
で、で起動するにはにスコープされますそれはで表示された機能、ないそれがであるブロックのであれば文が関数にスコープされる場合は内部で定義された任意のvar
(if文のような)関数内のブロックがある:。
function foo() {
if (1 === 1) {
var output = "Something";
}
console.log(output);
}
foo();
あなたはwith
ブロック内にあるとき、あなたはで動作するように、「コンテキスト」を指定します。あなたの場合、あなたはその場所で働いています。それはそれを見つけることができない場合は、変数を参照するとき、それは最初location
のコンテキストで変数を探します、それは関数スコープを見てみましょう:だから
function foo() {
var notInLocation = "something "; // Not as attribute of location
var pathname = "something else"; // Is as attribute of location
// the pathname in the location here seems to be "/js"
with (location) {
console.log(notInLocation + href); // href is a attribute of location and notInLocation isn't
console.log(pathname + href); // hred and pathname are both attributes in location
}
}
foo()
でwith
ブロックの場合、最初にlocation.qs
を試して、名前がqs
の属性を見つけられないので、関数スコープを調べて、先ほど定義した変数を選択します。
'with'ブロックの中で' var'で宣言された変数は、その周囲のスコープ( 'buildUrl')に追加されます。 'with'は、この点を除いて、グローバルな' window'オブジェクトと同様の働きをします。 Btw、 'with'はJavascriptでは非推奨です。この[ブログ記事](http://www.2ality.com/2011/06/with-statement.html)をご覧ください。 – ftor