Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Safely Extend Native Objects

Status
Not open for further replies.

atwork8

Programmer
May 3, 2008
3
GB
Hi All,

I've been looking at different javascript libraries for a while now to see what one suits best. The 2 I'm interested in are jQuery and mooTools. I've been messing with both and I really like them, however, the way they get the job done is completely different. I prefer the mooTools syntax as it is how javascript intended
e.g.

" lots of spaces before and after ".trim(); //mooTools
$.trim(" lots of spaces before and after "); //jQuery

But I hate how it pollutes and extends native objects, as it has caused us problems in the past with other scripts.

Now jQuery's one global symbol method is excellent and stops all the compatibility problems with other scripts, which is why I think we'll be going with jQuery. So my question is this, why doesn't jQuery and other frameworks apply the same compatibility method to Native types (exc Object) as it does to the global namespace? e.g.

Code:
var natives = {
        extend: function(sType,sAlias) {
            for(var e in this[sType]) {
                String.prototype[sAlias + e] = this[sType][e];
            }
        },
        'String': {
            trim: function() {
                return (this || "").replace(/^\s+|\s+$/g,"");
            },
            repeat: function(iCount) {
                for(var i = 0,str = '';i < iCount;i++) { str += this; }
                return str
            },
            format: function() {
                var a = arguments,i = -1;
                return this.replace(/#/g,function() { return a[++i] });
            }
        },
        'Array': {
            //extend array
        },
        'Date': {
            //extend date
        }
        //bla bla bla
    }

    natives.extend('String','$');
    alert('     lots of spaces before and after     '.$trim());
    alert('I love you ' + 'x'.$repeat(5));
    alert('hi #, want to go to the ##'.$format('John','foo','bar'));

In terms of the global namespace it's a tried and tested method so I'm sure it could work on Natives too, plus, it would mean jQuery javascript is more like javascript. It would be good to get some feedback on why this sort of thing isn't employed.

Thanks,

Reiss :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top