One of the ideological sticking points of the first JavaScript framework was was extending prototypes vs. wrapping functions. Frameworks like MooTools and Prototype extended prototypes while jQuery and other smaller frameworks did not. Each had their benefits, but ultimately all these years later I still believe that the ability to extend native prototypes is a massive feature of JavaScript. Let’s check out how easy it is to empower every instance of a primitive by extending prototypes!
Every JavaScript native, like Number
, String
, Array
, Object
, etc. has a prototype
. Every method on a prototype
is inherited by every instance of that object. For example, we can provide every `Array
instance with a unique
method by extending its prototype:
Array.prototype.unique = function() { return [...new Set(this)]; } ['1', '1', '2'].unique(); // ['1', '2'] new Array('1', '1', '2').unique(); // ['1', '2']
Note that if you can also ensure chaining capability by returning this
:
['1', '1', '2'].unique().reverse(); // ['2', '1']
The biggest criticism of extending prototypes has always been name collision where the eventual specification implementation is different than the framework implementation. While I understand that argument, you can combat it with prefixing function names. Adding super powers to a native prototype so that every instance has it is so useful that I’d never tell someone not to extend a prototype. #MooToolsFTW.
9 Mind-Blowing Canvas Demos
The
<canvas>
element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that…fetch API
One of the worst kept secrets about AJAX on the web is that the underlying API for it,
XMLHttpRequest
, wasn’t really made for what we’ve been using it for. We’ve done well to create elegant APIs around XHR but we know we can do better. Our effort to…
MooTools Clipboard Plugin
The ability to place content into a user’s clipboard can be extremely convenient for the user. Instead of clicking and dragging down what could be a lengthy document, the user can copy the contents of a specific area by a single click of a mouse.
Source link
Leave a Reply