Extend customized method in JavaScript

It can use prototype to define your own methods or properties. In String object example, there is no trim method provided by JavaScript. If we want to implement it and used in our own application. We can write this:
String.prototype.trim = function() {
    return this.replace(/^[\s]*/ig,'').replace(/[\s]*$/ig, '');
};


The customization method have to perform before used. After, I have trim method to deal with String. For example:
var b = ' abc def ';
b.trim(); // result is "abc def"

留言

熱門文章