JavaScript Quick Syntax Reference by Mikael Olsson

JavaScript Quick Syntax Reference by Mikael Olsson

Author:Mikael Olsson
Language: eng
Format: epub, pdf
Publisher: Apress, Berkeley, CA


Constructor Functions

Objects can be created from a constructor function. They provide features that classes provide in other languages, by allowing multiple instances of an object to be created from a single set of definitions. By convention, functions intended to be used as object constructors start with a capital letter, as a reminder of their purpose.

function Box(x, y) {

this.x = x;

this.y = y;

this.getArea = function() { return this.x * this.y; };

}

To instantiate one or more objects from this constructor the function is called with the new directive. Just like any other function, a constructor can accept arguments, as seen in this example.

var b1 = new Box(1, 2);

var b2 = new Box(3, 4);

Each object instance contains its own set of properties, which can hold values that are different from those of other instances.

console.log(b1.x); // "1"

console.log(b2.x); // "3"

The constructor function previously defined includes a function declared within another function. Such a nested function can access variables defined in its parent function, as it forms a so-called closure that includes the scope of the outer function. An advantage of this object creation pattern is that it provides information hiding. For instance, the following example has a method that uses a local variable to record how many times the method has been called. This feature is similar to private properties in class-based languages, as the local variable is only visible from within the constructor function.

function Counter(x, y) {

var count = 0;

this.printCount = function() { console.log(count++); };

}

var c = new Counter();

c.printCount(); // "0";

c.printCount(); // "1";

A small disadvantage of this object creation pattern is that each instance will have its own printCount method, which increases the memory consumed by each object. An alternative pattern that avoids this is to make use of inheritance to add the method to the object’s prototype instead.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.