【发布时间】:2017-03-26 16:00:24
【问题描述】:
这肯定是个微不足道的问题,但我对 JavaScript 有点困惑。我想在另一个函数中调用方法。我花了一些时间来处理这个问题,到目前为止我得到的只是第二段代码。我想知道,是否有评论中提到的类似解决方案。
function Student() {
this.greeting = function() {
alert('Hi! I\'m student.');
};
};
function Teacher() {
Student.call(this)
this.greeting = function() {
Student.??? // here I want something like "inherited", or call Student.greeting()
alert('and I like apples');
};
};
我想确定,没有像原型设计这样的其他选择:
function Student() {
};
Student.prototype.greeting = function() {
alert('Hi! I\'m student.');
};
function Teacher() {
Student.call(this);
this.greeting = function() {
Student.prototype.greeting();
alert('and I like apples');
};
};
感谢
【问题讨论】:
-
这看起来像你正在尝试使用带有类继承的阴影,这不符合 JavaScript 的精神,它使用原型链来链接对象。通过委托给其他对象(例如使用 Object.create),您可以通过 `[[Prototype]]' 链接访问这些方法。
标签: javascript