開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js, Safari(JavaScript エンジン)
- Learning JavaScript [邦訳](参考書籍)
メタプログラミングRuby 第2版(Paolo Perrotta (著)、角 征典 (翻訳)、オライリージャパン)の1部(メタプログラミング Ruby)、2章(月曜日: オブジェクトモデル)、2.4(メソッドを呼び出すときに何が起きているの?)、2.4.2(メソッドの実行)、self キーワード (this キーワード)、トップレベル、クラス定義とself、privateの本当の意味 を JavaScript で取り組んでみる。
HTML5
<button id="run0">run</button> <button id="clear0">clear</button> <pre id="output0"></pre> <script src="sample7.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'),
btn1 = document.querySelector('#clear0'),
pre0 = document.querySelector('#output0'),
p = (x) => pre0.textContent += x + '\n';
let pObj = (o) => {
Object.keys(o).forEach((k) => {
p(`${k}: ${o[k]}`);
});
};
let MyClass = (spec) => {
let that = {},
v,
testingSelf = () => {
v = 10;
myMethod();
return that;
},
myMethod = () => {
v += 1;
return v;
};
that.v = () => v;
that.testingSelf = testingSelf;
that.myMethod = myMethod;
return that;
};
let MyClass1 = (spec) => {
let that = {};
return that;
};
let C = (spec) => {
let that = {},
publicMethod = () => {
return that.privatemethod();
},
privatemethod = () => {};
that.publicMethod = publicMethod;
return that;
};
let C1 = (spec) => {
let that = {},
publicMethod = () => {
return privatemethod();
},
privatemethod = () => {};
that.publicMethod = publicMethod;
return that;
};
let topLevel = this;
let output = () => {
p('selfキーワード');
let obj = MyClass();
pObj(obj);
p(obj.v());
pObj(obj.testingSelf());
p(obj.v());
p('トップレベル');
p(window);
p(topLevel);
p(window === topLevel);
p('クラス定義とself');
p(MyClass1());
p('privateの本当の意味');
p('C');
let c = C();
try {
p(c.publicMethod());
} catch (e) {
p(e.type);
p(e.message);
}
p('C1');
let c1 = C1();
try {
p(c1.publicMethod());
} catch (e) {
p(e.type);
p(e.message);
}
};
btn0.onclick = output;
btn1.onclick = () => {
pre0.textContent = '';
};
output();
0 コメント:
コメントを投稿