In JavaScript, how do I inherit from a parent class in child class using a single ".prototype" block? -


for example:

function person() {     //person properties     this.name = "my name"; }  person.prototype = {     //person methods     sayhello: function() {         console.log("hello, person.");     }      saygoodbye: function() {         console.log("goodbye");     } }  function student() {     //student specific properties     this.studentid = 0; }  student.prototype = {     //i need student inherit person     //i.e. equivalent of     //student.prototype = new person();     //student.prototype.constructor = person;      //student specific methods     //override sayhello     sayhello: function() {         console.log("hello, student.");     } } 

i know can achieve using:

function student() {     this.studentid = 0; }  student.prototype = new person(); student.prototype.constructor = person; student.prototype.sayhello = function () {     console.log("hello, student."); } 

but i'd continue use style first example , have class methods defined in single ".prototype" block if possible.

take @ following answer on stackoverflow: https://stackoverflow.com/a/17893663/783743

this answer introduces concept of prototype-class isomorphism. put prototype object can used model class. following code taken above answer:

function class(prototype) {     var constructor = prototype.constructor;     constructor.prototype = prototype;     return constructor; } 

using above method can implement person follows:

var person = class({     constructor: function () {         this.name = "my name";     },     sayhello: function () {         console.log("hello, person.");     },     saygoodbye: function () {         console.log("goodbye");     } }); 

inheritance requires additional work. let's modify class function little:

function class(prototype, base) {     switch (typeof base) {     case "function": base = base.prototype;     case "object": prototype = object.create(base, descriptorof(prototype));     }      var constructor = prototype.constructor;     constructor.prototype = prototype;     return constructor; } 

we need define descriptorof function class work:

function descriptorof(object) {     return object.keys(object).reduce(function (descriptor, key) {         descriptor[key] = object.getownpropertydescriptor(object, key);         return descriptor;     }, {}); } 

now can create student follows:

var student = class({     constructor: function () {         this.studentid = 0;     },     sayhello: function () {         console.log("hello, student.");     } }, person); 

see demo yourself: http://jsfiddle.net/cadu2/

if need understanding code feel free contact me.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -