JavaScript gives us the ability to create new types of objects using constructors. So, one of the ways creating an object is to use the Object type constructor:
var person = new Object();
Once the person 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.
Let’s create a constructor:
function User(pName, pAge) {//it is customary to write the names of constructors with a capital letter this.name = pName;//let's set the property of the object through the constructor this.age = pAge;//let's set the property of the object through the constructor this.displayInfo = function () {//let's set the method of the object through the constructor document.write("Name: " + this.name + "; age: " + this.age); }; }
A constructor is a normal function, except that we can set properties and methods in it. For installation properties and methods use the this keyword.
After that, in the program, we can create an object of type User using the keyword new.
var person = new User("Alexander", 33); console.log(person.name); //Alexander person.displayInfo();
Similarly, we can define other types and use them together:
function Car(mName, mYear) { this.name = mName; this.year = mYear; this.getCarInfo = function () { document.write("Model: " + this.name + " Year: " + this.year); }; }; function User(pName, pAge) { this.name = pName; this.age = pAge; this.driveCar = function (car) { document.write(this.name + " drive car " + car.name); }; this.displayInfo = function () { document.write("Name: " + this.name + "; age: " + this.age); }; }; var person = new User("Alexander", 33); var personcar = new Car("BMW", 2004); user.driveCar(personcar);
instanceof operator
The instanceof operator allows you to check which constructor an object was created with. If the object is created with of a specific constructor, then the operator returns true:
var person = new User("Alexander", 33); var isUser = person instanceof User; console.log(isUser);// true