Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
In JavaScript, you can add functions and attributes to all instances of an object by adding those functions and attributes to the object’s prototype using the aptly named prototype attribute.
In CoffeeScript we can do this using the :: operator. Let’s add a size function to all instances of array. We want the size function to return the length of the array.
Example: (source: prototypes.coffee)
myArray = [1..10]
try
console.log myArray.size()
catch error
console.log error
Array::size = -> @length
console.log myArray.size()
myArray.push(11)
console.log myArray.size()
Example: (source: prototypes.js)
(function() {
var myArray;
myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
try {
console.log(myArray.size());
} catch (error) {
console.log(error);
}
Array.prototype.size = function() {
return this.length;
};
console.log(myArray.size());
myArray.push(11);
console.log(myArray.size());
}).call(this);