2009-11-09 48 views
5

我正要在javascript中创建一个修剪功能,但由于我不想重新发明轮子,因此我使用了此方法。
我发现这个链接 http://www.somacon.com/p355.php我应该修改String的原型吗?

它提供的解决方案是:

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+$/,""); 
} 

如果你还don'y Wnt信号改变字符串的原型,然后使用这个它说:

function trim(stringToTrim) { 
    return stringToTrim.replace(/^\s+|\s+$/g,""); 
} 
function ltrim(stringToTrim) { 
    return stringToTrim.replace(/^\s+/,""); 
} 
function rtrim(stringToTrim) { 
    return stringToTrim.replace(/\s+$/,""); 
} 

我想知道在什么情况下应该不是修改String的原型或者说任何对象。

回答

7

trim功能是ECMAScript中第五版标准化,以及已经存在于某些浏览器。所以:

  1. 是,将它们添加到原型是完全适当的,但

  2. 你不应该将它们添加到原型,如果他们已经在那里,因为你只被替换快速的本地代码功能与一个缓慢的JavaScript之一。

它通常也稍快做装饰两个替代对象:

// Add ECMA262-5 string trim if not supported natively 
// 
if (!('trim' in String.prototype)) { 
    String.prototype.trim= function() { 
     return this.replace(/^\s+/, '').replace(/\s+$/, ''); 
    }; 
} 
+1

+1 for'if(!('('String.prototype'trim')){' – 2009-11-09 12:04:25

+0

if(!String.prototype.trim)有什么问题?看起来对我更有效率。 – KooiInc 2009-11-09 15:20:19

+3

'in'更明确地表明它正在测试什么,不依赖于某个属性的真实性,或者针对任何其他语言会认为是异常的东西,重新调整一个新的“未定义”的奇怪和可怕的JavaScript怪癖。对于这个特殊的情况当然根本不重要,但是一般情况下我总是使用'in'来测试对象是否有属性。 – bobince 2009-11-09 19:11:54

1

对于这种非常有用的实用功能,我会说你可以修改原型。 但是你应该知道,该功能可能已经在一些浏览器本身存在的,所以你应该检查一下:https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/String

+0

在这种情况下,您不应该是它涉及一些开销或什么? – 2009-11-09 11:24:27

+0

有没有“你不应该”的情况下,只是要知道法比恩说什么。 – 2009-11-09 11:38:47

+0

伟大的JavaScript 1.8.1是有string.trim()方法https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Trim – 2009-11-09 11:54:19

2

一般 - 不修改原型的buildin对象。 但是,您可以添加您的便利功能。

而且经常检查你添加前:

//pre-1.6 javascript 
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(elt) { 
     var len = this.length >>> 0; 
     var from = Number(arguments[1]) || 0; 
     from = (from < 0) ? Math.ceil(from) : Math.floor(from); 
     if (from < 0) 
      from += len; 
     for (; from < len; from++) { 
      if (from in this && this[from] === elt) 
       return from; 
     } 
     return -1; 
    }; 
} 

这样,你没有覆盖玉米粥更快的buildin功能可能会提供一段时间...

相关问题