javascript - How can I properly organize my JS code into a more traditional class structure? -


i'm struggling js code structure that's becoming apparent during unit testing attempts. i'm used class structure, i'm bit lost in js world there aren't classes. i'm looking way organize code in traditional class/constructor architecture. here's have:

function ddgridselector(primaryid, templatedefault, gridobj) {     //set variables     this.primaryid = primaryid,     this.defaulttemplate = templatedefault,     this.gridobj = gridobj,     this.gridobj.searchval = '',      this.init = ddgs_init }  function ddgs_init(ddgs_obj) {     ddgs_setdefaulttemplate(ddgs_obj);     ddgs_initgrid(ddgs_obj);     ddgs_initkendowindow(ddgs_obj);     ddgs_initkendobutton(ddgs_obj);     ddgs_initresetbutton(ddgs_obj);     ddgs_addgrideventlistener(ddgs_obj); }  function ddgs_setdefaulttemplate(ddgs_obj) {     //doing stuff }  function ddgs_initgrid(ddgs_obj) {     //more stuff } 

to call of these...

var ddgridselector_new = new ddgridselector('primaryidentifier', templatedefault, gridobj);  ddgridselector_new.init(ddgridselector_new); 

it seems redundant pass object function that's specified in constructor i'm sure i'm missing obvious here. appreciate guidance on matter. think i'm close being on path.

es5 way

you can "functional classes" this, pretty self explainable:

function user(name) {   // name "private" here because it's   // not put under "this.name"    this.sayhi = function() {     alert(name);   }; }  let user = new user("john"); user.sayhi(); // john 

there's prototype class pattern well:

function user(name, birthday) {   this._name = name; }  user.prototype.sayhi = function() {   alert(this._name); };  let user = new user("john"); user.sayhi(); // john 

source/tutorial examples listed here

es6+ way

in es6 can declare classes in way looks more traditional programming languages:

class user {    constructor(name) {     this.name = name;   }    sayhi() {     alert(this.name);   } }  let user = new user("john"); user.sayhi(); // john 

however need transplier babel or typescript compile down web compatible code if targeting platforms such ie (all versions), opera mini, , android browser (4.4.x, ~16% of android versions in field) (web compat sources), or things such cordova on older ios devices (< 10, uiwebview, etc).

node.js should have support classes 4.8.4(!) , above, surprisingly enough (source).


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -