StrugglingCoder
StrugglingCoder

Reputation: 5021

Prototypal Inheritence in Node JS

Being from the classical Inheritance Background(C#,Java etc.) , I am struggling with the Prototypal Way of doing it. I am not understanding the basics also . Please explain and correct me on the following code block.

    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());

But the error I am getting is enter image description here

What was I missing ?

Upvotes: 0

Views: 112

Answers (1)

jfriend00
jfriend00

Reputation: 708206

There is no standard this.super_ property so I'm not sure where you got that from. If you're using util.inherits(), you can see a nice simple example of how to use it in the nodejs doc for util.inherits().

And, here's how your code could work:

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);

FYI, in ES6 syntax, there is a super keyword which is part of a new way of declaring Javascript inheritance (still prototypal) you can read about here.

Upvotes: 1

Related Questions