Javascript Class Constructor Call Method -
in java phone call methods help heavy lifting in constructor, javascript requires method defined first, i'm wondering if there's way go or if i'm forced phone call method heavy lifting after it's been defined. prefer maintain instance functions contained within object/class, , feels weird have have constructor @ end of object/class.
function polynomials(polystring) { // instance variables this.polys = []; this.left = undefined; this.right = undefined; // not work because it's not yet declared this.parseinit(polystring); // parses out string , initializes this.left , this.right this.parseinit = function(polystring) { //lots of heavy lifting here (many lines of code) } // lot more instance functions defined downwards here (even more lines of code) // alternative phone call here? }
here's do:
var polynomials = function() { // let's utilize self invoking anonymous function // can define var / function without polluting namespace // thought build class homecoming it, while taking advantage // of local scope. // constructor definition function polynomials( value1) ( this.property1 = value1; instancecount++; // here can utilize publicmethod1 or parseinit } // define public methods of class on prototype. polynomials.prototype = { publicmethod1 : function() { /* parseinit()... */ }, getinstancecount : function() ( homecoming instancecount; } } // can define functions won't pollute namespace here // functions private class (that can't accessed inheriting classes) function parseinit() { } // can define vars private class // obvious illustration instance count. var instancecount = 0; // homecoming class-function built; homecoming polynomials; }();
remarks:
rq 1:
prototype functions public methods available each instance of class.
var newinstance = new myclass(); newinstance.functiondefinedonprototype(samevalue);
rq2: if want 'private' variable, have got way:
function constructor() { var privateproperty=12; this.functionusingprivateproperty = function() { // here can utilize privateproperrty, it's in scope } } constructor.prototype = { // here define public methods uses public properties publicmethod1 : function() { // here privateproperty cannot reached, out of scope. } }
personally, utilize properties (not private vars), , utilize '' mutual convention notify property private. can define every public method on prototype. after that, using property prefixed '' must take his/her responsibility , seems fair. :-)
for difference between function fn() {}
, var fn= function() {}
, google or s.o. question, short reply function fn() {}
gets function defined , assigned value in whole scope, when var
var defined, value evaluated when code has run evaluation.
javascript class methods constructor
No comments:
Post a Comment