jquery - Javascript Inheritance Best Strategy -
currently have built our own javascript framework building widgets, divs, panels , forms our complex web application. our widgets (aka. components) inherit super object called viewable defines view htmlelememnt.
viewable = { getview: function() { if (!this.view) this.view = this.createview(); return this.view; } createview: function() { alert(‘you have not implemented createview. naughty boy!); } }
then use object.create(viewable) create our own components, need implement createview defined in viewable.
header = object.create(viewable); header.createview = function() { var div = document.createelement('div'); div.id = 'header'; } header.foobar = function() { }
i move away type of inheritance, create-object-on-the-fly , add methods on depending on mood.
i have looked @ other approach using $.extends jquery. can create object (or better ‘define function’? ‘defined class’?)
function header() { $.extend(true, this, viewable); this.createview = function() { var div = document.createelement('div'); div.id = 'header'; } this.foobar = function() { } }
i refactor code second approach because me benefits :
- you constructor
- there degree of encapsulation
- it resembles oo languages java (i come world..)
- my ide (webstorm) likes better intellisense , refactoring.
but not sure. there drawbacks? have refactor 50+ files, little nervous doing this. still relatively new javascript.
also while @ it, quick sub-question. if refactored viewable :
function viewable() { this.getview = function() { if (!this.view) this.view = this.createview(); return this.view; }, createview:function() { alert(‘you have not implemented createview. naughty boy!); } }
would more beneficial? because me makes code consistent.
javascript has no class definitions (yet), no interfaces. add methods on depending on mood how prototypical inheritance works.
using object.create
or $.extend
not change this.
keep in mind $.extend
not give inheritance tree. header instanceof viewable
false
, you're copying properties defined on viewable
. $.extend
object merge modifies input argument.
if instanceof
not important can use either method.
es6 has new ideas on how class definitions in javascript. es6 not implemented yet if want workable preview can have @ microsoft's typescript. typescript not 100% compatible es6 it's compatible matters.
typescript adds classes , interfaces , jazz. gives type hints want, removed when compiled javascript.
Comments
Post a Comment