我想通过应用经典继承在扩展的 javascript“类”中调用 super 方法。
function Person(name, age) {
this._name = name;
this._age = age;
}
Person.prototype.exposeInfo = function() {
alert(this._name + ' - ' + this._age);
}
function Employee(name, age) {
this.parent.constructor.call(this, name, age);
}
Employee.prototype.exposeInfo = function() {
alert('Call employee');
this.parent.exposeInfo();
}
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;
var p1 = new Person('John Doe', 30);
p1.exposeInfo();
var p2 = new Employee('John Foobar (empl.)', 35);
p2.exposeInfo();
问题是方法没有在扩展类中调用,而只在父类(Person)中调用。
最佳答案
那是因为重写的 exposeInfo
被附加到以前的 prototype
对象,然后被替换:
Employee.prototype = Object.create(Person.prototype);
您需要颠倒顺序,在创建 prototype
之后附加方法:
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;
Employee.prototype.exposeInfo = function() {
// ...
}
您还需要将 .call()
或 .apply()
与 exposeInfo
一起使用,就像您对构造函数所做的那样:
Employee.prototype.exposeInfo = function() {
alert('Call employee');
this.parent.exposeInfo.apply(this, arguments);
}
否则,this
的值将由最后一个成员运算符决定:
// so, calling:
this.parent.exposeInfo();
// is equivalent to:
alert(this.parent._name + ' - ' + this.parent._age);
关于Javascript 经典继承调用父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568319/