我正在学习面向对象的 Javascript,但我不禁觉得我错过了给定练习的机会。所以我在这里寻找的是关于如何改进我的代码或对构造函数的理解的指示。这是 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();
这是我的回应,在一两个帐户上失败了,但我对它的实际结构更感兴趣。我完全偏离基地了吗?有什么地方可以查看浏览器实现的实际 String 构造函数以进行比较吗?
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;
}
我要去 sleep 了,但我会在早上起来回复。非常感谢您就此问题提供的任何指导。
最佳答案
如前所述,关于类结构的简要说明。
您的类是以这样一种方式编写的,以便所有方法都在构造函数中。因此,当您初始化一个新类时,所有方法都会重新生成。因此,如果您在页面上有多个 MyString 类的实例,这将不是最有效的技术。您应该考虑改用原型(prototype)制作技术。所以你的构造函数将简单地变成:
function MyString(string){
a = string.split("");
this.length = a.length;
}
然后您的方法在构造函数外部声明,因此不会在每次创建 MyString 的新实例时重新生成。
MyString.prototype.toString = function(){ return a.join(""); }
MyString.prototype.charAt = function(index){ return a[index]; }
关于javascript - 重写 JS 字符串构造函数 : Am I Way Off?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3888273/