Javascript经典继承调用父

时间:2013-10-24 14:08:31

标签: 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)中调用。

2 个答案:

答案 0 :(得分:4)

那是因为覆盖的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);

答案 1 :(得分:0)

if(mysqli_num_rows($query) == 0){

它不起作用。

示例:

// ...

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;

Employee.prototype.exposeInfo = function() {
  this.parent.exposeInfo.apply(this, arguments);
  // ...
}

正确版本:

// ...

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.parent = Person.prototype;

Employee.prototype.exposeInfo = function() {
  this.parent.exposeInfo.apply(this, arguments);
  // ...
}

ParttimeEmployee = Object.create(Employee.prototype);
ParttimeEmployee.prototype.constructor = ParttimeEmployee;
ParttimeEmployee.prototype.parent = Employee.prototype;

ParttimeEmployee.prototype.exposeInfo = function() {
  this.parent.exposeInfo.apply(this, arguments);
  // ...
}

var p1 = new Person('Jack', 30);
p1.exposeInfo(); // ok

var p2 = new Employee('Jane', 25);
p2.exposeInfo(); // ok

var p3 = new ParttimeEmployee('John', 20);
p3.exposeInfo(); // infinite recursion !!!