【问题标题】:Javascript calling prototype method from constructor with parameters [duplicate]Javascript从带有参数的构造函数调用原型方法[重复]
【发布时间】:2017-11-11 15:59:42
【问题描述】:

我试图从教授构造函数内部调用 Person.showInfo(),并将其名称和年龄作为参数。可能吗?。请看下面的评论谢谢。

var Person = function(_name, _age) {
    this.name = _name;
    this.age = _age;
}

Person.prototype.showInfo = function() {
    console.log(this.name, this.age);
};

var Professor = function(_name, _age, _course) {
    Person.call(this, _name, _age);
    this.course = _course;
};

Professor.prototype = Object.create(Person.prototype);
Professor.prototype.constructor = Professor;

Professor.prototype.showInfo = function() {
    // How to call Person.showInfo() here ???
    // Person.prototype.showInfo() ...showing the Professor's name and age
    console.log(this.course);
};

【问题讨论】:

  • 那么就没有办法实现多态了吗?

标签: javascript oop methods constructor


【解决方案1】:
Person.prototype.showInfo.call(this);

只需按原样调用函数,但更改上下文。

【讨论】:

  • 这正是我所说的。谢谢
猜你喜欢
  • 2015-10-10
  • 1970-01-01
  • 2015-04-06
  • 1970-01-01
  • 2015-10-30
  • 2018-11-01
  • 2016-12-21
  • 2018-05-09
  • 2013-05-08
相关资源
最近更新 更多