プロトタイプ
function Hoge() { var self = this; this.foo = foo; } function foo() {}
と書くより
function Hoge() {} Hoge.prototype.foo = function() {}
と書くとオブジェクトごとの関数へのポインタを持つことなく効率的に使用出来るのがプロトタイプチェーンを使う利点の一つらしい。
継承もプロトタイプ使うのが一般的らしい。
function Human() {} Human.prototype = { hello : function() { alert("Hello."); } }; function Student() {}; Student.prototype = { study : function() { alert("Ah...Help me."); } }; function extends(sub, super) { for(var i in super.prototype) { sub.prototype[i] = super.prototype[i]; } }; extends(Student, Human); var st = new Student(); st.hello(); // "Hello."
何か継承というより追加の方がピンとくる。
プロトタイプの取得/再設定が出来る「__proto__」プロパティを利用すればもっと簡単に出来る。
Student.prototype.__proto__ = Human.prototype; var st = new Student(); st.hello(); //"Hello"