LoginSignup
2
2

More than 5 years have passed since last update.

スクラッチパッド(Firefox)のトップレベルでのvarの挙動で気になったところ

Last updated at Posted at 2015-01-14

まずは下記のHTMLをブラウザで開いてみてください

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>`var` test</title>
</head>
<body>
<script>
var A = "hoge";
B = "fuga";

document.write("(this === window) = " + (this === window) + ", A = " + this.A + ", B = " + this.B + "<br>");

delete this.A;
delete this.B;

document.write("(this === window) = " + (this === window) + ", A = " + this.A + ", B = " + this.B + "<br>");
document.close();
</script>
</body>
</html>

の記述の通り、トップレベルのコンテキストでのvarにより宣言された変数はグローバルオブジェクト(トップレベルにおいてthisで参照でき、通常ブラウザではwindowでも参照できる)の変更不可能(configurable: false)なプロパティとなり、deleteを行っても何も変化はありません。1

そのため、表示は以下の通りになります(Chrome 39, Firefox 34, IE 11で確認)

(this === window) = true, A = hoge, B = fuga
(this === window) = true, A = hoge, B = undefined

しかし、Firefox 34で空のドキュメントを開いている状態でスクラッチパッドを開き、

var A = "hoge";
B = "fuga";

document.write("(this === window) = " + (this === window) + ", A = " + this.A + ", B = " + this.B + "<br>");

delete this.A;
delete this.B;

document.write("(this === window) = " + (this === window) + ", A = " + this.A + ", B = " + this.B + "<br>");
document.close();

を実行した場合は表示は以下の通りになります

(this === window) = true, A = hoge, B = fuga
(this === window) = true, A = undefined, B = undefined

このコンテキストでのthis.Aが変更不可能となっていません。そもそもthis.A自体が作成されないのであれば

(function() {
  // ここ
}).call(this);

の中身として実行されているとも解釈できるのですが、それとも異なるようです。
実際どうなのかは詳しく調べないとわからないと思うのですが、少なくともトップレベルとはこのような挙動の違いがあることは確かです。


  1. strictモード時は未宣言の変数への代入B = "fuga";および変更不可能なプロパティの削除delete this.A;が実行時エラーとなります。 

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2