Chapter 8. Function Prototype Property

Conceptual Overview of the Prototype Chain

The prototype property is an object created by JavaScript for every Function() instance. Specifically, it links object instances created with the new keyword back to the constructor function that created them. This is done so that instances can share, or inherit, common methods and properties. Importantly, the sharing occurs during property lookup. Remember from Chapter 1 that every time you look up or access a property on an object, the property will be searched for on the object as well as the prototype chain.

Note

A prototype object is created for every function, regardless of whether you intend to use that function as a constructor.

Below, I construct an array from the Array() constructor, and then I invoke the join() method.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

var myArray = new Array('foo', 'bar');

console.log(myArray.join()); // logs 'foo, bar'

</script></body></html>

The join() method is not defined as a property of the myArray object instance, but somehow we have access to join() as if it were. This method is defined somewhere, but where? Well, it is defined as a property of the Array() constructor’s prototype property. Since join() is not found within the array object instance, JavaScript looks up the prototype chain for a method called join().

Okay, so why are things done this way? Really, it is about efficiency and reuse. Why should every array instance created from the array ...

Get JavaScript Enlightenment now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.