A JavaScript Constructor is a function which is used as a constructor that allows you to create an object from a class. A constructor access is one of public, protected and private.
Three ways to define a JavaScript class,
1. Using as a function
2. Using as Object Literals
3. Singleton using as a function
The Syntax
access NameOfAClass(parameters) { initialization code; }
//Access as public public customer(parameters) { initialization code; }
//Access as protected protected customer(parameters) { initialization code; }
//Access as private private customer(parameters) { initialization code; }
Examples as,
//class declaration inJavaScript //constructor var customer = function (id, name, age) { } customer.prototype = {} //Instance variables members. var customer = function (id, name, age) { this.id = id; this.name = name; this.age = age; } customer.prototype = {} //Static variables. var customer = function (id, name, age) { this.id = id; this.name = name; this.age = age; } customer.prototype = { staticVar1: 20, staticVar2: 'Anil' } //Instance functions methods. var customer = function (id, name, age) { this.id = id; this.name = name; this.age = age; } customer.prototype = { getId: function () { return this.id; }, setId: function (id) { this.id = id; } } //Static functions var customer = function (Id, name, age) { this.id = id; this.name = name; this.age = age; } customer.create = function (Id, name, age) { return new customer(Id, name, age); } customer.prototype = {}
Stayed Informed - 39 Best Object Oriented JavaScript QA
What happens
when a constructor is called?
1. It creates a
new object.
2. It sets the
constructor property of the object to Vehicle.
3. It sets up the
object to delegate to customer.prototype.
4.
It calls customer()
in the context of the new object.