2 level inheritance in javascript -
i trying accomplish 2 levels of inheritance in javascript without framework.
**class --> model --> listmodel** ideally code should this
var class = function(){} var model = new class; var listmodel = new model; after implementation come next solution smells badly.
var class = function(){ klass = function(){}; klass.extend = function(){ console.log("extend")} klass.prototype.include = function(){ console.log("include") }; homecoming klass } var model = function(parent){ var model = function(){ } if(parent){ for(var in parent){ model[i] = parent[i]; } for(var in parent.prototype){ model.prototype[i] = parent.prototype[i]; } } model.record = [1,2]; model.prototype.generateid = function(){ console.log("genrate id")}; homecoming model } var listmodel = function(parent){ if(parent){ for(var in parent){ listmodel[i] = parent[i]; } for(var in parent.prototype){ listmodel.prototype[i] = parent.prototype[i]; } } } var class = new class() var model = new model(class) var l = new listmodel(model) can help me in improve way.
i utilize function called defclass define "classes" (actually constructors) don't inherit else:
function defclass(prototype) { var constructor = prototype.constructor; constructor.prototype = prototype; homecoming constructor; } using defclass can create classes follows:
var model = defclass({ constructor: function (...) { // init code }, somemethod: function (...) { // } }); when comes inheritance need more. wrote own extend function:
function extend(constructor, keys) { var supertype = keys.super = constructor.prototype; var prototype = object.create(supertype); (var key in keys) prototype[key] = keys[key]; homecoming defclass(prototype); } using extend can inherit other classes follows:
var listmodel = extend(model, { constructor: function (...) { // init code }, somemethod: function (...) { // override default implementation // utilize `this.super` gain access overridden methods }, someothermethod: function (..) { // else } }); simple isn't it?
javascript inheritance
No comments:
Post a Comment