LoginSignup
2
2

More than 5 years have passed since last update.

【メモ】JavaScriptで継承(っぽいの)

Last updated at Posted at 2014-02-14

継承

// 簡単な継承。雑
var Hoge = function(){};
var Piyo = function(){};
Hoge.prototype = Piyo.prototype;
// 簡単な継承
function inherit(oldCls, object){
  var newCls = function(){};
  newCls.prototype = oldCls.prototype;
  for(var prop in object){
    if(!object.hasOwnProperty(prop)){ continue; }
    newCls.prototype[prop] = object[prop];
  }
  newCls.prototype.constructor = newCls;
  return newCls;
}

n番煎じだと思うJSの継承のメモ書き。
extendは拡張、inheritが継承 と英単語的には違うらしいのでいつも悩んだりします。

クラス定数…

public static String CONST_HOGE = 'hoge';
のような定数が作れたとすると、上記のロジックでは継承することが出来ないです。

for(var prop in object){
  if(!object.hasOwnProperty(prop)){ continue; }
  newCls[prop] = oldCls[prop];
}

たぶんこんな感じになる。

そもそも

出力すると分かるんですが…。
objectが持っているプロパティをすべてnewCls.prototypeに入れちゃっているので、
インスタンスを作った時に、__proto__の中にいて、まるで

「僕も継承されちゃったんですよ☆」

みたいな状態になってて凄く腹ただしい。
ただコンストラクタ関数でthis.barと宣言するか、instance.fooのようにインスタンスオブジェクトに付けないと出てこないので、

考えるのをやめた。

ともあれ

JavaScriptでそこまで継承をすることは(現状私には)ないし、
ちょっと足りないので、まぁいいかなと。
プロトタイプチェーンの勉強にはなると思いますが。
というかプロトタイプチェーンの話のためのネタですよね???

2
2
4

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
2
2