Javascript parent child inheritance without using prototype

I'm a bit new to JavaScript. I know you should use a prototype to implement inheritance between objects, but I tried the following and it worked fine (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 check obj it has properties for Person and Student, and I can call obj.name () to get "Abe Lincoln". Even in the immediate Visual Studio window, I can see all the properties as siblings of each other, as I would expect. But I am not using a prototype, so obviously this is wrong.

Set me up straight :)

Thanks in advance!

+3


source to share


1 answer


To use prototypal inheritance, you must place the method name

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 object .prototype

object an Student

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

      

So now your method is being name

used for all instances created instead of having to re-do them for each instance.

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

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

      

+1


source







All Articles