JavaScript Object constructors

In addition to creating new objects, JavaScript gives us the ability to create new types of objects using constructors. So, one way to create an object is to use the Object type constructor:

[Js]
var tom = new Object();
[/Js]

Once the tom variable is created, it will behave like an object of type Object.

The constructor allows you to define a new type of object. A type is an abstract description or template of an object. You can also draw the following analogy. We all have some idea of ​​a person – having two arms, two legs, a head, a digestive system, a nervous system, and so on. There is some template – this template can be called a type. A really existing person is an object of this type.

A type definition can consist of a constructor function, methods, and properties.

First, let’s define a constructor:

[Js]
function User(pName, pAge) {
this.name = pName;
this.age = pageAge;
this.displayInfo = function(){
document.write(“Name: ” + this.name + “; age: ” + this.age + “
“);
};
}
[/Js]

A constructor is a normal function, except that we can set properties and methods in it. This keyword is used to set properties and methods :

[Js]
this.name = pName;
[/Js]

In this case, two properties’ name and age and one displayInfo method are set.

As a rule, the names of constructors, unlike the names of ordinary functions, begin with a capital letter.

After that, in the program, we can define an object of type User and use its properties and methods:

[Js]
var tom = new User(“Том”, 26);
console.log(tom.name); // Том
tom.displayInfo();
[/Js]

To call the constructor, that is, to create an object of type User, you must use the new keyword.

Similarly, we can define other types and use them together:

[Js]
// constructor of type Car
function Car(mName, mYear){
this.name = mName;
this year = mYear;
this.getCarInfo = function(){
document.write(“Model: ” + this.name + ” Year: ” + this.year + “
“);
};
};
// User type constructor
function User(pName, pAge) {
this.name = pName;
this.age = pageAge;
this.driveCar = function(car){
document.write(this.name + ” drives ” + car.name + “
“);
};
this.displayInfo = function(){
document.write(“Name: ” + this.name + “; age: ” + this.age + “
“);
};
};

var tom = new User(“Tom”, 26);
tom.displayInfo();
var bently = new Car(“Bentley”, 2004);
tom.driveCar(bently);
[/Js]

instanceof operator

The instanceof operator allows you to check which constructor an object was created with. If the object is created using a specific constructor, then the operator returns true:

[Js]
var tom = new User(“Tom”, 26);

var isUser = tom instance of User;
var isCar = tom instanceof Car;
console.log(isUser); // true
console log(isCar); // false
[/Js]