Javascript 经典继承调用父级

标签 javascript inheritance super

我想通过应用经典继承在扩展的 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();

JS Fiddle

问题是方法没有在扩展类中调用,而只在父类(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/

相关文章:

javascript - Object.create 多个原型(prototype)

java - 子类使用 "this"调用父类(super class)方法

python - Python 3 中的 Django 问题 "super() argument 1 must be type, not WSGIRequest"

javascript - VM456 :22 Uncaught ReferenceError: wndow is not defined

javascript - 成员查询复杂度 : Python Vs. Javascript

c# - 确保在 C# 中调用基方法

java - 什么是 PECS(生产者扩展消费者 super )?

Java通配符具有 super 意外的行为

javascript - 使用 Javascript 隐藏 CSS 下拉菜单

javascript - Node.js 或 Ubuntu Linux 在服务器启动时运行 cron