開発環境
- 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.3(Refinements)、Refinements を捕まえた、を JavaScript で取り組んでみる。
HTML5
<button id="run0">run</button> <button id="clear0">clear</button> <pre id="output0"></pre> <script src="sample8.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'), p = (x) => pre0.textContent += x + '\n'; let StringExtentions = (spec) => { let that = {}, defaultToAlphanumeric = String.prototype.toAlphanumeric, defaultReverse = String.prototype.reverse, defaults = [['toAlphanumeric', defaultToAlphanumeric], ['reverse', defaultReverse]], on = () => { String.prototype.toAlphanumeric = function () { return this.replace(/[^\w\s]/g, ''); }; String.prototype.reverse = () => { return 'esrever'; }; }, off = () => { defaults.forEach((x) => { String.prototype[x[0]] = x[1]; }); }; that.on = on; that.off = off; return that; }; let StringStuff = (spec) => { let that = {}, se = StringExtentions(); se.on(); p('myString'.reverse()); se.off(); return that; }; let MyClass = (spec) => { let that = {}, myMethod = () => 'original myMethod', anotherMethod = () => myMethod(); that.myMethod = myMethod; that.anotherMethod = anotherMethod; return that; }; let output = () => { let se = StringExtentions(); try { p('my *1st* refinement!'.toAlphanumeric()); } catch (e) { p(e); } se.on(); try { p('my *1st* refinement!'.toAlphanumeric()); } catch (e) { p(e); } se.off(); try { p('my *1st* refinement!'.toAlphanumeric()); } catch (e) { p(e); } StringStuff(); p('Refinements を捕まえた'); let obj = MyClass(); let t = obj.myMethod; obj.myMethod = () => 'refined myMethod'; p(obj.myMethod()); p(obj.anotherMethod()); obj.myMethod = t; p(obj.myMethod()); p(obj.anotherMethod()); }; btn0.onclick = output; btn1.onclick = () => { pre0.textContent = ''; }; output();
0 コメント:
コメントを投稿