Augmenting Built-in Objects

The built-in objects such as the constructor functions Array, String, and even Object, and Function can be augmented through their prototypes, which means that you can, for example, add new methods to the Array prototype and in this way make them available to all arrays. Let's do this.

In PHP there is a function called in_array() that tells you if a value exists in an array. In JavaScript there is no inArray() method, 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) {
      return true;
    }
  }
  return false;
}

Now all arrays will have the new method. Let's test:

>>> var a = ['red', 'green', 'blue']; >>> a.inArray('red'); ...

Get Object-Oriented JavaScript 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.