javascriptでprototypeを使って継承させる(親クラスに引数ありの場合)
prototypeプロパティを使ってjavascriptでのクラス継承を実現させる方法。親クラスに引数がないときには、
var MySub = function () { /* .... */ }: MySub.prototype = new MySuper(); var sub = new MySub();
でいいのだが、サブクラスのインスタンス生成時に指定した引数を親クラスにも継がせたい場合はうまくいかないので、以下の方法にしてみた。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xml:lang="ja" xmlns="http://www.w3.org/1999/xhtml" lang="ja"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>javascript prototype inheritance test</title> <script type="text/javascript"> var MySuper = function(s) { this.supers = s; alert('super constructor : ' + this.supers); }; var MySub = function (s) { this.subs = s; this.superclass(this.subs); }; MySub.prototype.superclass = MySuper; var sub = new MySub("test"); alert(sub.subs); alert('inheritance property : ' + sub.supers); </script> </head> <body> <h1>javascript prototype inheritance test</h1> </body> </html>
superclassがポイント。