applyとprototypeの動き
applyはプロパティに入れたいため、prototypeにnewを入れるのは変更時に継承元側を書き換えないようにするため
なのかな?よくわからん。
applyが良くわからなくて、「初めてのJavaScript」のp.244継承の例を勉強。
<html> <head> <script type="text/javascript"> function tune(title,type) { this.title = title; this.type = type; this.getTitle = function () { return "title:" + this.title + " type:" + this.type; } } function artist_tune(title, type, artist) { this.artist = artist; this.toString("アーティストは" + artist); // これ何の処理だ? tune.apply(this,arguments); this.toString = function () { return 'artist:' + this.artist + ' ' + this.getTitle(); } } artist_tune.prototype = new tune(); var song = new artist_tune("A", "B", "C"); alert(song.toString()); for (var property in artist_tune.prototype) { // new tune()をやらないと空 alert(property); } </script> </head> <body> </body> </html>
- artist_tuneはapplyにthisとパラメタを渡すことでtuneのプロパティを自分(this)のプロパティにしてる
- artist_tuneのprototypeにtuneをnewして代入することでartist_tuneのprototypeにtuneのプロパティを代入
なのかなと思ったのだけど、
artist_tune.prototype = new tune();
ここがやっぱりわからないな。たとえばartist_tune.prototype.getTitleでgetTitleを編集してからnewしてもapplyで上書きされちゃうよね。
prototypeに入れる利点がわからない。。