with文 (JavaScript)
[履歴] [最終更新] (2013/07/29 02:40:14)
最近の投稿
注目の記事

概要

C++におけるusing namespaceや、Pythonのfrom importのようなものです。多用しすぎると名前空間が汚染されてバグの原因となりますが、適切に使用すれば記述がシンプルになります。

sample.js

var obj = {scope1: {x:1, y:2, z:3}, scope2: {x:-1, y:-2, z:-3}};

console.log(obj.scope1.x);
with(obj.scope1) {
    console.log(y);
    console.log(z);
}

console.log(obj.scope2.x);
with(obj.scope2) {
    console.log(y);
    console.log(z);
}

実行例

$ node sample.js 
1
2
3
-1
-2
-3

なお、以下のようにしても記述量を削減できます。

var obj = {scope1: {x:1, y:2, z:3}, scope2: {x:-1, y:-2, z:-3}};

var s1 = obj.scope1;
console.log(s1.x);
console.log(s1.y);
console.log(s1.z);

var s2 = obj.scope2;
console.log(s2.x);
console.log(s2.y);
console.log(s2.z);
関連ページ