Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 483
GamingDaemon Avatar asked Jan 17 '26 17:01

GamingDaemon


1 Answers

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");
like image 162
the system Avatar answered Jan 20 '26 08:01

the system



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!