I'm on my way through Object Oriented Javascript, and I can't help but feel I've missed the boat on a given exercise. So what I'm looking for here is pointers on how I can improve my code or understanding of Constructors. Here was the challenge:
Imagine the String() constructor didn't exist. Create a constructor function MyString() that acts like String() as closely as possible. You're not allowed to use any built-in string methods or properties, and remember that String() doesn't exist. You can use this code to test your 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 was my response, which fails on one or two accounts, but I'm more interested in the actual structure of it. Am I completely off-base? Is there somewhere I can view the actual String constructor implemented by browsers to compare?
function MyString(string){
a = 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 to bed, but I'll be up and responding in the morning. Thanks so much for any guidance you can give on this issue.