LoginSignup
3
3

More than 5 years have passed since last update.

withによるブロックスコープ構文

Posted at

JavaScriptでブロックスコープと言えば即時関数(function(){ ... })()ですが、もう一つwithを使った構文があります。しかし動作がすさまじく遅いので使いどころは微妙です。

withスコープ(あらかじめローカル変数をすべて宣言)
var a = "global";
with ({a:"local"}) {
  console.log(a); //"local"
  with ({a:"local2"}) {  /* 入れ子にできる */
    console.log(a); //"local2"
  }
  console.log(a); //"local"
}
console.log(a); //"global"

動的にローカル変数を追加したい場合はこんな書き方でいけます。varではなくmy.~でローカル変数を宣言します。

無名コンストラクタを併用して動的にローカル変数を追加できるようにした
var a = "global";
with (new function(){this.my=this}) {
  console.log(a); //"global"
  my.a = "local"; //ローカル変数を追加した
  console.log(a); //"local"
}

console.log(a); //"global" ブロックを抜けたのでグローバル変数に戻る
3
3
1

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
3
3