Loading lesson path
Concept visual
Start at both ends
Sometimes we need to create many objects of the same type. To create an object type we use an object constructor function.
Formula
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;
}Try it yourself » In the constructor function, this has no value. The value of this will become the new object when a new object is created.
JavaScript Object this.
to create many new Person objects:
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");Try it yourself »
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 a created object is easy:
Example myFather.nationality = "English";The new property will be added to myFather. Not to any other Person Objects.
add a new property to an object constructor:
Person.nationality = "English";To add a new property, you must add it to the constructor function prototype:
Person.prototype.nationality = "English";Example function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}Adding a method to a created object is easy:
Example myMother.changeName = function (name) {
this.lastName = name;
}The new method will be added to myMother. Not to any other Person Objects.
You cannot add a new method to an object constructor function. This code will produce a TypeError:
Person.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");TypeError: myMother.changeName is not a function Adding a new method to a constructor must be done to the constructor function prototype:
Person.prototype.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
The changeName() function assigns the value of name to the person's lastName property, substituting this with myMother.Formula
JavaScript has built - in constructors for all native objects:new Object() // A new Object object new Array() // A new Array object new Map() // A new Map object new Set() // A new Set object new Date() // A new Date object new RegExp() // A new RegExp object new Function() // A new Function object
object is not in the list.
Math is a global object. The new keyword cannot be used onMath.
{}
instead of new Object().[] instead of new Array().
/()/ instead of new RegExp().