Photo by GLUEKITS
すみません。下記記事は間違っています。近々訂正記事を書きます。
→訂正記事
Javascriptでクラスベースっぽく書いてる時に、継承したくなった場合の書き方。
ググってもすぐ出なかったのでメモ。
IE6,7,8 Firefox2,3,3.5 Safari 3,4で確認。
p.s
node.jsに、MySQLドライバがないので、書き始めました。
<html> <body> <div id="result"></div> <script> var puts = function(str) { var el = document.getElementById('result'); el.innerHTML = el.innerHTML + str + "<br/>"; } var Parent = function(n) { this.n = n; } Parent.prototype = Array.prototype; Parent.prototype.display1 = function() { puts("display1:"+this.n); } Parent.prototype.display2 = function() { puts("display2: ERROR"); } var Child = function(n) { Parent.apply(this, [n*2]); // 親クラスのコンストラクタを呼ぶ } Child.prototype = Parent.prototype; Child.prototype.display2 = function() { puts("display2(over):"+this[0]); } Child.prototype.display3 = function() { puts("display3:"+this.n); } var child = new Child(1); child.push(10); child.push(20); child.display1(); child.display2(); child.display3(); </script></body> </html>
os0x
Parent.prototype = Array.prototype;
はまずいです。
Parent.prototypeはArray.prototypeでもあるわけで、display1 はすべての配列のメソッドとなってしまいます。
Child.prototype = Parent.prototype;
も同じくです。
一応、 http://nanto.asablo.jp/blog/2006/10/18/566348 あたりはそれなりに使えますが、Arrayに関してはlengthがネックになって完全な継承を行うことはできません。
http://d.hatena.ne.jp/sawat/20070221/cant_extends_array
masuidrive
おお、そうですね。ご指摘ありがとうございます。
調べて訂正記事を書きます。