Javascript从父类(super class)调用方法

标签 javascript

我尝试在学生对象的 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'

Example Fiddle

关于Javascript从父类(super class)调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719009/

相关文章:

javascript - 使用 JS/jQuery 将项目附加到存储在变量中的列表

Javascript RegExp 用于将文本拆分为带引号的句子并保留分隔符

javascript - 使用 javascript 保持粘性使 div 超出父级

javascript - 在 React 中导入文件的不同方式

c# - 如何解码用 JavaScriptStringEncoded 编码的字符串?

javascript - 在接近的水线处严格或

javascript - 仅在指定字符的第一个实例上拆分字符串

javascript - DataTables 动态添加列到表

javascript - js setTimeout递归返回-继续

javascript - 是否有悬停或 mouseenter/mouseleave 的切换?