1. ホーム
  2. javascript

[解決済み] javascriptでクラスを継承する方法は?

2022-12-26 10:35:33

質問

PHP/Javaで、こんなことができます。

class Sub extends Base
{
}

そして、自動的にスーパークラスのすべてのパブリック/プロテクトされたメソッド、プロパティ、フィールドなどがサブクラスの一部となり、必要に応じてオーバーライドすることができます。

Javascriptでそれに相当するものは何ですか?

どのように解決するのですか?

私は今、この方法を変更しました。コンストラクタ関数とその prototype プロパティを使用しないようにしていますが、2010年からの古い回答はまだ一番下にあります。私は現在 Object.create() . Object.create は、すべてのモダンブラウザで利用可能です。

注意すべきは Object.create は通常 より遅い を使うより new を関数コンストラクタで使うよりも遅いです。

//The prototype is just an object when you use `Object.create()`
var Base = {};

//This is how you create an instance:
var baseInstance = Object.create(Base);

//If you want to inherit from "Base":
var subInstance = Object.create(Object.create(Base));

//Detect if subInstance is an instance of Base:
console.log(Base.isPrototypeOf(subInstance)); //True

jsfiddle

Object.createを使う大きなメリットの1つは、オブジェクトに defineProperties 引数を渡すことができることです。これにより、クラスのプロパティにアクセスし、列挙する方法を大幅に制御できます。また、私はインスタンスを作成するために関数を使用していますが、これらはインスタンスを返すだけでなく、最後に初期化を行うことができるので、ある意味でコンストラクタとして役に立ちます。

var Base = {};

function createBase() {
  return Object.create(Base, {
    doSomething: {
       value: function () {
         console.log("Doing something");
       },
    },
  });
}

var Sub = createBase();

function createSub() {
  return Object.create(Sub, {
    doSomethingElse: {
      value: function () {
        console.log("Doing something else");
      },
    },
  }); 
}

var subInstance = createSub();
subInstance.doSomething(); //Logs "Doing something"
subInstance.doSomethingElse(); //Logs "Doing something else"
console.log(Base.isPrototypeOf(subInstance)); //Logs "true"
console.log(Sub.isPrototypeOf(subInstance)); //Logs "true

jsfiddle

これは2010年の私のオリジナルの解答です。

function Base ( ) {
  this.color = "blue";
}

function Sub ( ) {

}
Sub.prototype = new Base( );
Sub.prototype.showColor = function ( ) {
 console.log( this.color );
}

var instance = new Sub ( );
instance.showColor( ); //"blue"