2012-10-12 28 views
2

我已經使用了應答here作爲例子stringToSlug()函數原型,雖然我更願意把它寫這樣的:value.stringToSlug()JavaScript創建

所以我把它改成這樣:

// String to slug 
String.prototype.stringToSlug = function(str) { 
     str = str.replace(/^\s+|\s+$/g, ''); // trim 
     str = str.toLowerCase(); 
     str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars 
       .replace(/\s+/g, '-') // collapse whitespace and replace by - 
       .replace(/-+/g, '-'); // collapse dashes 
     return str; 
}; 

它的工作原理,如果我通過這樣的字符串:

var value = $(this).val(); 
value.stringToSlug(value); 
+0

是否有另一種方式來獲得字符串的值,而不把它當作一個PARAM? –

回答

11

如果你修改任何原型你可以採取的事實優勢指對象本身;在這種情況下,它指向你調用的方法的字符串:

String.prototype.stringToSlug = function() { // <-- removed the argument 
    var str = this; // <-- added this statement 

     str = str.replace(/^\s+|\s+$/g, ''); // trim 
     str = str.toLowerCase(); 
     str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars 
       .replace(/\s+/g, '-') // collapse whitespace and replace by - 
       .replace(/-+/g, '-'); // collapse dashes 
     return str; 
}; 

然後調用這樣的:

$(this).val().stringToSlug(); 
+0

這是問題的正確答案,但我也建議不要這樣做。這樣做並沒有真正的優勢,並且它使得代碼的可移植性稍差。 – Paul

+1

@Paul:「沒有優勢」和「便攜性」是什麼意思? –

+1

@Paul我總是對使用JavaScript擴展原生對象的原型感到不安的感覺:) –