Basically, because of the Object type. Extension of native objects is done in javascript through the "prototype" method. This adds functionality to each native object, allowing you to do things like:
"".trim() The problem arises with the Object native. This encompasses a large portion of the structures (all objects, classes, arrays, etc) in Javascript, and cannot be prototyped easily. The reason being, if you do something like: Object.prototype.myMethod = function(){ alert('Foo'); } You can no longer iterate through the object safely. Now: var a = {a:1,b:2,c:3}; $.each(a, function(key){ alert(key) }); // a,b,c,myMethod Also, keeping jQuery in the global namespace helps prevent conflict with libraries who go directly for native extension, like prototype.js On Jan 14, 8:19 pm, atwork8 <atwo...@hotmail.co.uk> wrote: > First post on here so hello everybody :o) > > 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 have to > admit, 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 apply > the same compatibility method to Native types (exc Object) as it does > to the global namespace? e.g. > > 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