GamingDaemon
GamingDaemon

Reputation: 31

Javascript parent child inheritance without using prototype

I'm somewhat new to JavaScript. I know that you should use prototype to implement inheritance between objects, but I tried the following and it worked perfectly (using Visual Studio 2012). What am I doing wrong?

function Person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    this.eyecolor = eyecolor;

    this.name = function() {
        return this.firstname + " " + this.lastname;
    }
}

function Student(firstname, lastname, age, eyecolor, level) {
    this.level = level;
    Person.call(this, firstname, lastname, age, eyecolor);
}

var per = new Person("Abe", "Lincoln", 45, "green");

var obj = new Student("Abe", "Lincoln", 45, "green", "senior");

When I examine obj, it has properties for Person and for Student, and I can call obj.name() to get "Abe Lincoln". Even in the Visual Studio immediate window, I can see all of the properties as siblings of one another, as I would expect. But I am not using prototype, so obviously this is not right.

Set me straight please :)

Thanks in advance!

Upvotes: 3

Views: 1890

Answers (1)

the system
the system

Reputation: 9336

To use prototypal inheritance, you'd put the name method on Person.prototype:

function Person(firstname, lastname, age, eyecolor) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    this.eyecolor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstname + " " + this.lastname;
}

Then make the .prototype object of Student an instance of Person:

function Student(firstname, lastname, age, eyecolor, level) {
    this.level = level;
    Person.call(this, firstname, lastname, age, eyecolor);
}

// Make the prototype object of the Student constructor inherit from the
//    prototype object of the Person constructor.
Student.prototype = Object.create(Person.prototype)

And so now your name method is shared among all instances created instead of being remade for each instance.

var per = new Person("Abe", "Lincoln", 45, "green");

var obj = new Student("Abe", "Lincoln", 45, "green", "senior");

Upvotes: 1

Related Questions