Chapter 9. Prototypes and Inheritance (The Function Object)

The latter half of Lesson 8 taught you how to create your own data types by creating a constructor function in conjunction with the this variable to create properties and methods. We'll pick up with the Point data type; its code is repeated here for your convenience:

function Point(x, y) {
    this.x = x;
    this.y = y;
    this.getDistance = function(point) {
        var x = Math.pow(point.x - this.x, 2);
        var y = Math.pow(point.y - this.y, 2);

        return Math.sqrt(x + y);

This implementation has a slight flaw. When calling the constructor with the new keyword, JavaScript creates a Point object, and in doing so it has to recreate everything within the constructor every time it's called. That is, the x and y properties, and a new Function object to serve as the getDistance() method. In JavaScript, functions are objects, too — complete with their own properties and methods.

In an object-oriented environment, creating a new object should also create its properties. Properties, and more importantly their values, are specific to each instance of a data type, and they should rarely be shared with all other instances of a particular data type. For example, a Point object's x and y properties contain values that are independent from another Point object's x and y properties. Changing one Point's x property should not affect another Point object's x property. So a Point's x and y properties should be created when the Point object is created.

A Point ...

Get JavaScript® 24-Hour Trainer now with O’Reilly online learning.

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