ECMAScriptなんて嫌な思い出しかないし、本当はもう金輪際触れたくもないのだがNode.js試運転 - らんだむな記憶してみたし、まぁ、見てみるかぁ。
クラス - JavaScript | MDNを丸パクしつつ
class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } } let animal1 = new Animal("Harry"); animal1.speak(); let animal2 = new Dog("Potter"); animal2.speak();
でドドン。
$ node a.js Harry makes a noise. Potter barks.
春からはじめるモダンJavaScript / ES2015 - QiitaやES2015 (ES6)についてのまとめ - Qiitaも参考にしてモダンにいこうか。
トランスコンパイラとしてTypeScriptを使ってみる。またMSか!という気持ちもあるが、本当に2016年1番人気はTypeScriptなのか? - Qiitaによると一番人気とかいう噂もあるようなのでミーハーになってみる。
TypeScript - JavaScript that scales.の通りにNode.jsのパッケージとして放り込む。
$ sudo npm install -g typescript
うっほ、拡張子として .tsが要求される。なんだかえむぺぐとぅーを思い出してしまうが忘れよう。
$ tsc a.ts a.ts(3,10): error TS2339: Property 'name' does not exist on type 'Animal'. a.ts(7,22): error TS2339: Property 'name' does not exist on type 'Animal'. a.ts(13,22): error TS2339: Property 'name' does not exist on type 'Dog'.
あー、うざっ。JSなんだから型とかよろしくやれよな(ぶつぶつ)
ということで先のスクリプトの先頭に
interface Animal { name: string; }
を補ってドン。
。゜゜(´□`。)°゜。ふぇぇぇん。なんですかー、この汚いのゎー
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Animal = (function () { function Animal(name) { this.name = name; } Animal.prototype.speak = function () { console.log(this.name + ' makes a noise.'); }; return Animal; }()); var Dog = (function (_super) { __extends(Dog, _super); function Dog() { return _super.apply(this, arguments) || this; } Dog.prototype.speak = function () { console.log(this.name + ' barks.'); }; return Dog; }(Animal)); var animal1 = new Animal("Harry"); animal1.speak(); var animal2 = new Dog("Potter"); animal2.speak();