0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[JavaScript] プロトタイプチェーンをいじって継承元を変更する

Last updated at Posted at 2022-02-20

環境

  • Node.js v16.14.0

詳細

JavaScript のプロトタイプチェーンをいじれば人を神(のサブクラス)にすることもできる。

'use strict';

class God {
  destroy() {
    console.log('Destroy!');
  }
}

class Animal {
  hunt() {
    console.log('Hunt!');
  }
}

class Human extends Animal {
  hack() {
    console.log('Hack!');
  }
}

const isAnimal = (target) => target instanceof Animal;
const isHuman = (target) => target instanceof Human;
const isGod = (target) => target instanceof God;

const adam = new Human();

console.log(isAnimal(adam)); // true
console.log(isHuman(adam));  // true
console.log(isGod(adam));    // false

adam.hunt();
adam.hack();
// adam.destroy(); できない

Object.setPrototypeOf(Human.prototype, God.prototype); // 人を神(のサブクラス)にする
// 以下と等価(__proto__ は ECMAScript 標準ではないので非推奨)
// adam.__proto__.__proto__ = God.prototype;

console.log(isAnimal(adam)); // false
console.log(isHuman(adam));  // true
console.log(isGod(adam));    // true

// adam.hunt(); できない
adam.hack();
adam.destroy(); // できる!
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?