javascript - Rewriting the JS String Constructor: Am I Way Off? -


i'm on way through object oriented javascript, , can't feel i've missed boat on given exercise. i'm looking here pointers on how can improve code or understanding of constructors. here the challenge:

imagine string() constructor didn't exist. create constructor function mystring() acts string() closely possible. you're not allowed use built-in string methods or properties, , remember string() doesn't exist. can use code test constructor:

--

var s = new mystring('hello');

s.length(); s[0]; s.tostring(); s.valueof(); s.charat(1); s.charat('2'); s.charat('e'); s.concat(' world!'); s.slice(1,3); s.slice(0,-1); s.split('e); s.split('l'); s.reverse();

and here response, fails on 1 or 2 accounts, i'm more interested in actual structure of it. off-base? there somewhere can view actual string constructor implemented browsers compare?

function mystring(string){      = string.split("");      this.length = a.length;      this.tostring = function(){         return a.join("");     };      this.valueof = function(){         if(a.length > 0 && string !== 0 && string !== false && string !== undefined){             return true;         } else {             return false;         }     };      this.charat = function(index){         return a[index];     };      this.concat = function(addition){         return string + addition;     };      this.slice = function(begin, end){         var a2 = new array();          if(end < 0){             end = parseint(a.length) + end;         }         for(y = begin;y<end;y++){             a2 += a[y];         }          return a2;     };      this.split = function(splitter){         sppos = parseint(a.indexof(splitter));         var split1 = a.slice(0,sppos);         var split2 = a.slice(sppos + 1, a.length);         var joined = new array();         return joined.concat(split1.join(""), split2.join(""));     };      this.reverse = function(){         var ar = a.reverse();         return ar.join("");     };      return this; } 

i'm headed bed, i'll , responding in morning. guidance can give on issue.

a quick point structure of class, mentioned before.

your class written in such way methods inside constructor. when initialise new class methods regenerated. if have more 1 instance of class mystring on page won't efficient technique. should consider using prototyping technique instead. constructor become:

function mystring(string){     = string.split("");     this.length = a.length; } 

your methods declared outside constructor , such not regenerated each time new instance of mystring created.

mystring.prototype.tostring = function(){ return a.join(""); }  mystring.prototype.charat = function(index){ return a[index]; } 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -