JavaScriptでコンストラクタを使ってクラス継承を行う。

テスト駆動JavaScript

テスト駆動JavaScript

上記書籍に紹介されているコンストラクタを使ったクラス継承方法が、ちょっと説明不足に感じたので補足のためのメモを残しておきます。

検証コード

Step1

コード
(function(){
  console.log('@Step1');
  function Man(name){
    this.name = name;
  }
  var smith = new Man('smith');
  
  function SMan(name){
    this.name = 'Super ' + name;
  }
  SMan.prototype = Man.prototype;
  var sSmith = new SMan('smith');

  console.log(smith.name);
  console.log(smith instanceof Man);
  console.log(smith.constructor);

  console.log(sSmith.name);
  console.log(sSmith instanceof Man);
  console.log(sSmith instanceof SMan);
  console.log(sSmith.constructor);
}());
実行結果
@Step1
smith
true
function Man(name){
    this.name = name;
} 
Super smith
true
true
function Man(name){
    this.name = name;
} 
解説

SManのインストラクタのコンストラクタプロパティがManのものになっているので不十分です。

Step2

コード
(function(){
  console.log('@Step2');
  function Man(name){
    this.name = name;
  }
  var smith = new Man('smith');
  
  function SMan(name){
    this.name = 'Super ' + name;
  }
  SMan.prototype = Man.prototype;
  SMan.prototype.constructor = SMan;
  var sSmith = new SMan('smith');

  console.log(smith.name);
  console.log(smith instanceof Man);
  console.log(smith.constructor);

  console.log(sSmith.name);
  console.log(sSmith instanceof Man);
  console.log(sSmith instanceof SMan);
  console.log(sSmith.constructor);
}());
実行結果
@Step2
smith
true
function SMan(name){
    this.name = 'Super ' + name;
}
Super smith
true
true
function SMan(name){
    this.name = 'Super ' + name;
} 
解説

今度はManのインストラクタのコンストラクタプロパティがSManのものになっているので不十分です。

Step3

コード
(function(){
  console.log('@Step3');
  function Man(name){
    this.name = name;
  }
  var smith = new Man('smith');
  
  function SMan(name){
    this.name = 'Super ' + name;
  }
  SMan.prototype = (function(){
    function F() {}
    F.prototype = Man.prototype;
    return new F();
  }());
  SMan.prototype.constructor = SMan;
  var sSmith = new SMan('smith');

  console.log(smith.name);
  console.log(smith instanceof Man);
  console.log(smith.constructor);

  console.log(sSmith.name);
  console.log(sSmith instanceof Man);
  console.log(sSmith instanceof SMan);
  console.log(sSmith.constructor);
}());
実行結果
@Step3
smith
true
function Man(name){
    this.name = name;
}
Super smith
true
true
function SMan(name){
    this.name = 'Super ' + name;
} 
解説

両インストラクタのコンストラクタプロパティが期待したものになりました。

最後に

以上です。
指摘等あればコメント頂けると幸いです。