bochen421
bochen421

Reputation: 161

Inheritance in JS, inheriting properties and values

I am a beginner and can't understand how the prototypes and inheritance works in JavaScript. I am basing on the code here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance and I can't figure out how to inherit properties values, I can only get "methods". I think that maybe the more appropriate question is how to initiate fields of parent class when invoking a child object?

In accordance with the mentioned site, I wrote something like this:

    function Person(name, surname) {
        this.name = name;
        this.surname = surname;     
    } 
function Student(index) {
    this.index = index;
    Person.call(this);
}

Student.prototype = new Osoba ();//I tried to insert values here in the constructor, it doesn't work
Student.prototype.constructor = Student;

var x = new Student ('89890');//tried to insert additional values here in the constructor, it also doesn't work

Is there a way to create a student and give him also a name and surname?

I am a total noobie so please explain like you would explain to a 5 year old. PS. I have to do this in JS so please don't recommend different ways, it won't help me, thanks :)

Upvotes: 0

Views: 151

Answers (3)

Rodrigo Fonseca
Rodrigo Fonseca

Reputation: 944

var inherit = function(C, P) {
      var F = function(){}; // i created this "proxy" to isolate the Parent constructor
      F.prototype = P.prototype;
      C.prototype = new F();
};

var Person = function(name, surname) {
       this.name = name || '';
       this.surname = surname || '';

       this.getName = function () {
         return this.name;
       }

      this.getSurname = function () {
         return this.surname;
      }
};


var Student = function(index, name, surname) {
  this.index = index;
  Person.call(this, name, surname);
};

inherit(Student, Person);

var student = new Student(0, 'Rodrigo', 'Fonseca');
alert(student.getName());
alert(student.getSurname());

Upvotes: 0

Wiktor Zychla
Wiktor Zychla

Reputation: 48314

The correct approach would be to have your child constructor repeat required parameters.

function Student(index, name, surname) {
    this.index = index;
    Person.call(this, name, surname);
}

var s = new Student ('89890', 'Jan', 'Kowalski');

Btw. this

Student.prototype = new Osoba ();

is certainly a typo, instead have

Student.prototype = new Person();

and you really don't need parameters here. The prototype will be initialized with undefined in property values and this is perfectly legal.

Upvotes: 1

dfsq
dfsq

Reputation: 193301

You can change Student constructor to this one:

function Student(index, name, surname) {
    this.index = index;
    Person.call(this, name, surname);
}

call takes optional parameters so you can invoke Person with additional arguments to set name and surname own properties.

Upvotes: 0

Related Questions