我应该修改String的原型吗? [英] Should i modify the prototype of String?
问题描述
我正准备在 javascript 中创建一个修剪函数,但由于我不想重新发明轮子,所以我用谷歌搜索了这个方法.
我找到了这个链接http://www.somacon.com/p355.php
I was about to create a trim function in javascript, but as i don't want to reinvent the wheel i googled for this method.
I found this link
http://www.somacon.com/p355.php
它提供的解决方案是:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
return this.replace(/\s+$/,"");
}
还说如果你不想改变 String 的原型,那么使用这个:
also it says if you don'y wnt to change the prototype of String then use this:
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
我想知道在什么情况下应该不修改String的原型或者说任何对象.
I would like to know in what scenario one should not modify the prototype of String or say any object.
推荐答案
trim
函数将在 ECMAScript 第五版中标准化,并且已经存在于某些浏览器中.所以:
The trim
functions are to be standardised in ECMAScript Fifth Edition, as well as already being present in some browsers. So:
是的,将它们添加到原型中是完全合适的,但是
Yes, adding them to the prototype is totally appropriate, but
如果它们已经存在,您不应该将它们添加到原型中,因为您只会用慢速 JavaScript 函数替换快速的本机代码函数.
You shouldn't add them to the prototype if they're already there, as you'll just be replacing a fast native-code function with a slow JavaScript one.
作为两个替换进行修剪通常也稍微快一点:
It is also typically marginally faster to do trim as two replaces:
// Add ECMA262-5 string trim if not supported natively
//
if (!('trim' in String.prototype)) {
String.prototype.trim= function() {
return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
}
这篇关于我应该修改String的原型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!