「JavaScript/クラス」の版間の差分

削除された内容 追加された内容
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
Ef3 (トーク | 投稿記録)
タグ: 2017年版ソースエディター
186 行
ECMAScript/JavaScriptには複素数型がありません。
実装の触りだけですね実際に動くコードを観てみます。
;[https://paiza.io/projects/Rlo71iVwVjMgXZUzSWGxlw?language=javascript ES6版]:<syntaxhighlight lang="javascript" line>
class Complex {
constructor(xreal = 0, yimag = 0) {
thisreturn Object.assign(this,{ real, =imag x})
this.imag = y
return this
}
toString() { return `${this.real}+${this.imag}i` }
203 ⟶ 201行目:
console.info("a + b = " + a.cadd(b))
console.info("a - b = " + a.csub(b))
console.info("a instanceof Complex =>", a instanceof Complex)
</syntaxhighlight>
;[https://paiza.io/projects/K2o2gPvM_tBbIFd3XM-lAA?language=javascript ES5版]:<syntaxhighlight lang="javascript" line>
function Complex(xreal = 0, yimag = 0) {
thisreturn Object.assign(this, { real, =imag x})
this.imag = y
return this
}
Complex.prototype.toString = function() { return `${this.real}+${this.imag}i` }
220 ⟶ 216行目:
console.info("a + b = " + a.cadd(b))
console.info("a - b = " + a.csub(b))
console.info("a instanceof Complex =>", a instanceof Complex)
</syntaxhighlight>
;実行結果(ES6/ES5双方同じ):<syntaxhighlight lang="javascript" line>
a = 1+1i
b = 2+3i
a + b = 3+4i
a - b = -1+-2i
a instanceof Complex => true
true
</syntaxhighlight>
:ES5では、constructorに相当する関数がclassに対応するクロージャを提供します。
233 ⟶ 229行目:
:オブジェクトにcadd()メソッドを定義しています(ES/JSでは演算子オーバーロードできないので、名前付き関数にしました)。
;オブジェクトへのメソッドの追加:<syntaxhighlight lang="javascript">
Complex.prototype.csub = function(n) { return new Complex(this.real - n.real, this.imag - n.imag) }
</syntaxhighlight>
:ES5でもES6でも、オブジェクトの prototype にプロパティを追加することで、オブジェクトに新しいメソッドを追加することができます。