Node JS中的原型继承

时间:2016-01-09 20:44:28

标签: javascript node.js inheritance prototypal-inheritance

从经典的继承背景(C#,Java等)出发,我正在努力实现Prototypal方式。 我也不了解基础知识。请在以下代码块中解释并纠正我。

    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

我错过了什么?

1 个答案:

答案 0 :(得分:1)

没有标准的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继承(仍然是原型)的新方法的一部分,您可以阅读here