以下将实现您正在寻找的内容:(工作 jsFiddle)。它使用原型链来实现经典继承。
function AnotherMan(name) {
this.name = name;
}
function Mr(name) {
AnotherMan.call(this, name); // Call the superclass's constructor in the scope of this.
this.name = "Mr. " + name; // Add an attribute to Author.
}
Mr.prototype = new AnotherMan(); // Set up the prototype chain.
Mr.prototype.constructor = Mr; // Set the constructor attribute to Mr.
var mrBean = new Mr("Bean");
您可以将其概括为一个函数:(另一个正在工作的 jsFiddle)
function extend(subClass, superClass) {
var F = function() {};
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
subClass.superclass = superClass.prototype;
if(superClass.prototype.constructor == Object.prototype.constructor) {
superClass.prototype.constructor = superClass;
}
}
并像这样使用它:
function AnotherMan(name) {
this.name = name;
}
function Mr(name) {
Mr.superclass.constructor.call(this, name);
this.name = "Mr. " + name;
}
extend(Mr, AnotherMan);
var mrBean = new Mr("Bean");