我尝试在学生对象的 hello 函数中调用 doSomething 方法,而无需附加原型(prototype)。 Student 扩展了 Person 对象。
function Person(name){
this._name = name;
this.doSomething = function () {
console.log('doSomething');
}
}
function Student (name, grade) {
this._name = name;
this._grade = grade;
this.hello = function () {
//How i can call doSomething() here
}
}
最佳答案
您需要在构造函数中.call()
父级,以便Student
拥有Person
所做的一切,然后执行this .doSomething()
:
function Student (name, grade) {
Person.call(this, name); // extends
this._grade = grade;
this.hello = function () {
this.doSomething();
};
}
然后您可以从学生实例调用 hello()
:
var student = new Student("t","A")
student.hello(); // logs 'doSomething'
关于Javascript从父类(super class)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719009/