文森特回答了您的直接问题,但是如果您想建立一个真正的继承层次结构,您可以进一步扩展,您可以这样做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;
现在我们可以重复类似的过程来扩展 Reader,比如 VoraciousReader:
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