Object.setPrototypeOfが実装された
実装されたメソッド
Object.setPrototypeOf(target, proto)
targetオブジェクトのプロトタイプをprotoに設定する
返り値はtargetで、protoはオブジェクトまたはnullである必要がある
解説
ES5で導入された Object.getPrototypeOf のセット版である。
これにより __proto__ を使わなくても動的にプロトタイプをセットできるようになった。
例
オブジェクトに配列のメソッドを継承させる
arrayLike = { length: 3, 0: 'a', 1: 'b', 2: 'c' } arrayLike.forEach // undefined Object.setPrototypeOf(arrayLike, Array.prototype) // 『Array.prototype』をarrayLikeの『プロトタイプ』に設定する arrayLike.forEach // <Function>
継承を取り消す
Object.setPrototypeOf(arrayLike, null) arrayLike.forEach // undefined arrayLike.toString // undefined arrayLike.valueOf // undefined
継承先を挿げ替える
function Human(name) { this.name = name } Human.prototype.hello = function () { alert('私の名前は' +this.name+ 'です。') } function Cat(name) { this.name = name } Cat.prototype.hello = function () { alert('ミャ~\n(吾輩は' +this.name+ 'である)') } function transform(from, to) { //種族を跨いで変身させる能力 Object.setPrototypeOf(from, Object.getPrototypeOf(to)) // from.__proto__ = to.__proto__ と同じ } kimura = new Human('木村') kimura.hello() // "私の名前は木村です。" tama = new Cat('タマ') transform(kimura, tama) // 木村さんをタマをモデルに猫に変身させる kimura.hello() // "ミャ~\n((吾輩は木村である))"
実装されたバージョン
V8 3.24.22