Posted filed under Javascript.

Photo by spud murphy

 先ほどの記事のコードにミスがあり、継承を行うと、親クラスも書き換えてしまうバグがありました。コメントやTwitterで報告いただいた方々ありがとうございます。

 あの後、調べて見れると、あまりスマートに継承を実現する方法は無いみたいですが、ユーザが作ったクラス(StringなどのAtomic型を除く)は下記のコードで継承が行えます。
 特に、Array型を継承するのは、無理なようです。[]を上書きできないので、どうしようも無いみたいです。残念。

<body>
<div id="result"></div>
<script>
var puts = function(str) {
    var el = document.getElementById('result');
    el.innerHTML = el.innerHTML + str + "<br/>";
}


// クラスを継承する
extendClass = function(subClass, baseClass) {
   var inheritance = function() { };
   inheritance.prototype = baseClass.prototype;

   subClass.prototype = new inheritance();
   subClass.prototype.constructor = subClass;
   subClass.baseConstructor = baseClass;
   subClass.superClass = baseClass.prototype;
}

var Parent = function(n) {
    this.n = n;
}
Parent.prototype.display1 = function() {
    puts("parent display1:"+this.n);
}
Parent.prototype.display2 = function() {
    puts("parent display2:"+this.n*2);
}
 
 
var Child = function(n) {
    Child.baseConstructor.apply(this, [n*2]);
}
extendClass(Child, Parent);
 
Child.prototype.display2 = function() {
    puts("child display2(over):"+this.n*2);
}
 
Child.prototype.display3 = function() {
    puts("child display3:"+this.n);
}
 
var child = new Child(1);
child.display1();
child.display2();
child.display3();
puts("<hr/>");

var parent = new Parent(1);
parent.display1();
parent.display2();

</script></body>
</html>

参考 

Trackbacks/Pingbacks

  1.  とっても! ちゅどん(雑記帳) » Blog Archive » [訂正版] Javascriptでクラスを継承する – @masuidrive blog