US moters et prototypeurs (quels sont sur ce site) portent généralement une boîte à outils pratique de fonctions que nous avons créées (ou empruntées) que nous implémentons sur des objets javascript natifs pour que nos vies soient un peu plus faciles. Je voulais obtenir une liste ensemble de fonctions prototypées très utiles, mais uniquement des objets mises en œuvre sur des objets natifs (c'est-à-dire Alors, quels sont vos favoris? p>
PS: J'ai inclus à la fois des matières et des prototypes en tant que fonction écrite pour une bibliothèque est assez facile à porter à l'autre. p>
PPS: Je connais les arguments pour / contre le prototypage des objets javascript natifs, je préférerais éviter cette discussion ici. P> string.implément ({... code> dans motools). P>
5 Réponses :
Voici quelques-uns de mes favoris pour motools.
Fonctions de chaîne p>
Array.implement({ //compare two arrays to see if they are identical compare : function(arr, strict) { strict = strict || false; if (this.length != arr.length) return false; for (var i = 0; i < this.length; i++) { if ($type(this[i]) == "array") { if (!this[i].compare(arr[i])) return false; } if (strict) { if (this[i] !== arr[i]) return false; } else { if (this[i] != arr[i]) return false; } } return true; }, //remove non-unique array values unique : function() { for(var i = 0; i< this.length; i++) { var keys = this.indexesOf(this[i]); while (keys.length > 1) { this.splice(keys.pop(), 1); } } return this; }, //same as array.unshift, except returns array instead of count //good for using inline... array.lpush('value').doSomethingElse() lpush : function() { for (var i = arguments.length -1 ; i >= 0; i--){ this.unshift(arguments[i]); } return this; }, //get all indexes of an item in an array indexesOf : function(item) { var ret = []; for (var i = 0; i < this.length; i++) { if (this[i] == item) ret.push(i); } return ret; } });
//taken from http://prototype.lighthouseapp.com/projects/8886/tickets/351-new-swap-method-for-elements Element.addMethods({ swap: (function() { if ('swapNode' in document.documentElement) return function(element, other) { return $(element).swapNode($(other)); }; return function(element, other) { element = $(element); other = $(other); var next = other.nextSibling, parent = other.parentNode; element.parentNode.replaceChild(other, element); return parent.insertBefore(element, next); }; })() }); // extend the array object to support indexed insertions // submitted at http://prototype.lighthouseapp.com/projects/8886-prototype/tickets/356-arrayinsert Array.prototype.insert=function(element,where) { var slice1=this.slice(0,where); var slice2=this.slice(where); return new Array.concat(slice1,element,slice2); }; //extend the array object to support searching thrtough indexed arrays // if returnIndex is true, then return the keyName, else return the value from that cell Array.prototype.nextValue=function(startIndex,returnIndex) { for(var i=startIndex+1;i<this.length;i++){ if(this[i]){ return (returnIndex?i:this[i]); } } return null; }; //extend the array object to support searching thrtough indexed arrays // if returnIndex is true, then return the keyName, else return the value from that cell Array.prototype.prevValue=function(startIndex,returnIndex) { for(var i=startIndex-1;i>=0;i--){ if(this[i]){ return (returnIndex?i:this[i]); } } return null; };
Je ne me développe pas vraiment avec des prototypes ni des motools, mais je suppose que les choses suivantes seraient utiles dans ces cadres.
Remplacement de Native Math.Round () Strong> qui prend Second paramètre facultatif qui spécifie la précision: p> non () strong> méthode pour obtenir un prédicat annulé: P> objValues({a:1, b:2, c:3}); // [1, 2, 3]
objKeys({a:1, b:2, c:3}); // ["a", "b", "c"]
Objmap, objvalues et objkeys sont tous mis en œuvre dans des meubles (via une classe de hash).
J'aime comment la propriété est vérifiée avant la création, pour éviter toute nouvelle propriétés natales.
if(!Array.prototype.indexOf) { Array.prototype.indexOf = function(){ ... }; }
J'ai continué sur ce que TJ111 a commencé, voici ma petite addition:
Array.implement({ //calculate the sum of all integers sum: function() { var sum = this.reduce(function(a, b) { return a + b; }); return sum; } });
Finalement! Quelques compagnons de mousse!