class C {
value = 1
x() { return this.value }
y = function() { return this.value }
z = () => this.value
}
普通に実行するならどれも結果は同じ
const c1 = new C()
c1.x()
// 1
c1.y()
// 1
c1.z()
// 1
x はクラス構文の基本のメソッド定義方法で prototype に関数がセットされる
y と z は関数を代入してるので prototype ではなくインスタンスに関数がセットされる
prototype を直接操作したりするような場合はどっちにあるべきか考える必要あり
どっちでもいいなら prototype にあるほうが無駄が少ない
const c2 = Object.create(C.prototype)
c2.x
// f x() { return this.value }
c2.y
// undefined
y と z の違いはアロー関数を使ってるかどうか
アロー関数では arguments や this が作られない
この場合の this はそのインスタンスに固定される
メソッドを関数としてどこかに渡す場合には基本的にアロー関数にしておいたほうが良い
const { x, y, z } = c1
x()
// TypeError: Cannot read property 'value' of undefined
y()
// TypeError: Cannot read property 'value' of undefined
z()
// 1