javascript - Node JS 中的原型(prototype)继承

标签 javascript node.js inheritance prototypal-inheritance

来自经典的继承背景(C#、Java 等),我正在努力解决原型(prototype)方式的问题。 我也不了解基础知识。请解释并纠正以下代码块。

    var util = require ('util'); 

function Student(choiceOfStream) { 
    this.choiceOfStream = choiceOfStream;
}

Student.prototype.showDetails = function() {
    console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}

function ScienceStudent() {
    Student.call(this,"Science");
}

function ArtsStudent() {
    Student.call(this,"Arts");
}

util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);

var ArtsStudent = new ArtsStudent(); 
var ScienceStudent = new ScienceStudent(); 

ScienceStudent.prototype.MajorSubject = "Math";
ArtsStudent.prototype.MajorSubject = "Literature";

console.log(ArtsStudent.showDetails());
console.log(ScienceStudent.showDetails());

但是我收到的错误是 enter image description here

我错过了什么?

最佳答案

没有标准的 this.super_ 属性,所以我不确定你从哪里得到它。如果您使用 util.inherits(),您可以在 nodejs doc for util.inherits() 中看到一个关于如何使用它的简单示例。 .

并且,您的代码的工作方式如下:

var util = require ('util');

function Student(choiceOfStream) { 
    this.choiceOfStream = choiceOfStream;
}

Student.prototype.showDetails = function() {
    console.log("A student of "+this.choiceOfStream+" has a major in "+this.MajorSubject);
}

function ScienceStudent() {
    Student.call(this, "Science");
    this.majorSubject = "Math";
}

function ArtsStudent() {
    Student(this,"Arts");
    this.majorSubject = "Literature";
}

util.inherits(ScienceStudent,Student);
util.inherits(ArtsStudent,Student);
<小时/>

仅供引用,在 ES6 语法中,有一个 super 关键字,它是声明 Javascript 继承(仍然是原型(prototype))的新方法的一部分,您可以阅读 here .

关于javascript - Node JS 中的原型(prototype)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34698709/

相关文章:

javascript - 强制 jQuery ajax

javascript - 如何在方法中的 addEventListener 和 JavaScript 中的全局函数中的 removeEventListener 时调用 removeEventLisener

mysql - 如何在 node-mysql 查询后获取警告

node.js - 自定义响应消息,用于验证 Node js 中的所有必需参数

javascript - 如何在不使用 native 长度方法的情况下在javascript中获取字符串的长度

javascript - 获取水平滚动条的高度

javascript - MongoDB 搜索不返回相同字符串的文档

R:在对象生成器中使用事件绑定(bind)有条件地向 R6 对象添加新类

ios - 从 UITextField 继承的自定义类在 Swift 中不起作用(使用自定义 init)

c++ - 无法从派生指针访问公共(public)基成员