Vincentはあなたの直接の質問に答えましたが、さらに拡張できる真の継承階層を設定したい場合は、次のようにしますReader
。
個人クラスを作成します。
function Person(name) {
this.name = name;
}
Person.prototype.getName = function(){
alert('Person getName called for ' + this.name);
return this.name;
}
Readerクラスも作成します。
function Reader(name) {
// Calls the person constructor with `this` as its context
Person.call(this, name);
}
// Make our prototype from Person.prototype so we inherit Person's methods
Reader.prototype = Object.create(Person.prototype);
// Override Persons's getName
Reader.prototype.getName = function() {
alert('READER getName called for ' + this.name);
// Call the original version of getName that we overrode.
Person.prototype.getName.call(this);
return 'Something';
}
Reader.prototype.constructor = Reader;
そして今、私たちは同様のプロセスを繰り返して、たとえばVoraciousReaderでReaderを拡張することができます。
function VoraciousReader(name) {
// Call the Reader constructor which will then call the Person constructor
Reader.call(this, name);
}
// Inherit Reader's methods (which will also inherit Person's methods)
VoraciousReader.prototype = Object.create(Reader.prototype);
VoraciousReader.prototype.constructor = VoraciousReader;
// define our own methods for VoraciousReader
//VoraciousReader.prototype.someMethod = ... etc.
フィドル:
http: //jsfiddle.net/7BJNA/1/
Object.create:https ://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
Object.create(arg)
プロトタイプが引数として渡されたものである新しいオブジェクトを作成しています。
編集
この最初の答えから何年も経ちましたが、Javascriptは、class
JavaやC++などの言語から来ている場合に期待どおりに機能するキーワードをサポートしています。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes