0% found this document useful (0 votes)
10 views

avaScript Object Constructors

Uploaded by

pasiteg800
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

avaScript Object Constructors

Uploaded by

pasiteg800
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

avaScript Object Constructors

Object Constructor Functions

Sometimes we need to create many objects of the same type.

To create an object type we use an object constructor function.

It is considered good practice to name constructor functions with an upper-


case first letter.

Object Type Person

function Person(first, last, age, eye) {

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eye;

Note:

In the constructor function, this has no value.

The value of this will become the new object when a new object is created.

See Also:

The JavaScript this Tutorial


Now we can use new Person() to create many new Person objects:

Example

const myFather = new Person("John", "Doe", 50, "blue");

const myMother = new Person("Sally", "Rally", 48, "green");

const mySister = new Person("Anna", "Rally", 18, "green");

const mySelf = new Person("Johnny", "Rally", 22, "green");

Property Default Values

A value given to a property will be a default value for all objects created by
the constructor:

Example

function Person(first, last, age, eyecolor) {

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eyecolor;

this.nationality = "English";

Adding a Property to an Object

Adding a property to a created object is easy:


Example

myFather.nationality = "English";

Note:

The new property will be added to myFather. Not to any other Person
Objects.

You might also like