Inheritance within Javascript -
i'm studying concept of inheritance in javascript, , tutorial i'm looking @ uses code:
// define student class function student() { // call parent constructor person.call(this); } // inherit person student.prototype = new person(); // correct constructor pointer because points person student.prototype.constructor = student; my question is, why necessary both call parent constructor, person.call(this), , set student prototype equal new person object (i.e. student.prototype = new person();)?
there 2 separate issues deal with.
the first make sure new student objects inherit person objects. that's why student.prototype = new person(). makes student.prototype person student objects inherit whatever object inherits (from person.prototype).
the second apply behavior in person constructor new student objects. that's why person.call(this). technically not needed if person constructor doesn't have code modifies new object, it's still idea in case add code person later.
side note, when setting inheritance, it's better do:
student.prototype = object.create(person.prototype) ...and shim object.create if needed. way don't need invoke person constructor in order new object inherits person.prototype. again, not issue, there side effects in constructor undesired when setting inheritance.
Comments
Post a Comment