Constructors

Not all wooden and mechanical pencils write in black. They could write in red or some other color. A way of indicating this needs to exist. The way to do this is to use a constructor function. Constructor functions, if they exist, are called by the use of the new keyword when instantiating an object. If they do not, as in the previous examples, a default is called that does no special processing. Constructors are used to set up the object in an initial known state. They are also used to handle parameters passed to them during the creation of the object. In our example the pencils must be able to have different writing colors. The line to instantiate a colored pencil then needs to look something like this.

The earlier example Pencil ...

Get Oracle Database Ajax & PHP Web Application Development 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.