Tuesday 16 May 2017

Inheritance in Node: cannot set property 'myprop' of undefined

I have a real mess with inheritance in NodeJs. I come from Js, and I thought that inheritance'd work the same way as Js. But I'm having more problems than I expected (probably because I'm mistaking with the concepts of modules)

I have two classes: Person and Student. Student, obviously inherits from Person.

// Person.js
function Person(person){
  this.setName(person.name);
  this.setSurname(person.surname);
}

Person.prototype.setName=function(value){
  this.name=value;
}

Person.prototype.setSurname=function(value){
  this.surname=value;
}

module.exports = Person;

And the other one:

// Student.js    
const Person = require('./Person')
function Student(student){
  Person.call(student);
  this.setSubject(student.subject);
}

Student.prototype.setSubject=function(value){
  this.subject=value;
}

module.exports = Student;

When I call Person constructor from other script there is no problem:

//index.js
const Person = require('./models/Person');
const Student = require('./models/Student');
let myPerson = new Person({name:'John', surname:'Smith'}); //Works fine

But when I call the Student, on the Person.call(student) part starts my nightmare: In the Person constructor never arrives the constructor param. It's always undefined, so the message cannot read property name of undefined appears.

What am I forgetting? What is wrong? Why the param is not parsing?



via xale94

No comments:

Post a Comment