Augmenting built-in objects

The objects created by the built-in constructor functions such as Array, String, and even Object and Function can be augmented (or enhanced) through the use of prototypes. This means that you can, for example, add new methods to the Array prototype, and in this way you can make them available to all arrays. Let's see how to do this.

In PHP, there is a function called in_array(), which tells you if a value exists in an array. In JavaScript, there is no inArray() method (although in ES5 there's indexOf(), which you can use for the same purpose). So, let's implement it and add it to Array.prototype.

Array.prototype.inArray = function (needle) { for (var i = 0, len = this.length; i < len; i++) { if (this[i] === needle) { ...

Get Object-Oriented JavaScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.