来自超类的Javascript调用方法

时间:2015-04-18 15:02:20

标签: javascript

我在学生对象的hello函数中尝试调用方法doSomething而没有原型只是附加在此。学生扩展了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
    }
}

2 个答案:

答案 0 :(得分:2)

您需要.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'

Example Fiddle

答案 1 :(得分:1)

您的代码应该是(使用适当的JS类扩展名):

function Person(name){
    this._name = name;
}
Person.prototype.doSomething = function() {
    console.log('doSomething');
}

function Student (name, grade) {
    this._name = name;
    this._grade = grade;
}
Student.prototype = Object.create(Person.prototype); // extends
Student.prototype.hello = function  () {
    // Just call it like this:
    this.doSomething();
}