Book
Submodule 12.3: Constructor functions
Submodule 12.3: Constructor functions
Completion requirements
View
- Introduction to Constructor
- Constructor syntax
- Methods inside Constructor Functions
- Adding Properties and Methods
Constructor syntax
Let's take the example of the JavaScript Object
var myObject = {
name:"myName",
age:20,
job:"myJob"
};
and see how it can be converted to constructor function.
In this case, we would first create an object type using a constructor function:
function myObject (n,a,j) {
this.name= n;
this.age = a;
this.job=j;
}
In general in a constructor function:
- parameters are passed inside the function, in this case, n,a,j are the parameters.
- each property starts with the keyword this.
- this does not have any default value, the value will be defined when a new object will be created.
- the assignment symbol is been used between the property and the value that will be defined by the parameter
- each property is separated from the next one by a semicolon
To use the constructor function, we have to create an object. The way this object is created is by calling the constructor function with the new keyword.
Example:
var him = new myObject ("John","30","developer");
Now, the values given in the "him" object, have passed inside the constructor function.
We can call the constructor properties with the same logic that we use for the JavaScrip Objects.
For example, one of the ways to access the name property would be:
console.log(him.name);