Javascript Constructor Function
By Saket Bhatnagar••Beginner to Intermediate
constructor function
- 1A function which is used to create an object is known as constructor function.
- 2A constructor function behaves like blueprint or template for object , and there is no need to write code again and again
- 3 It helps us to create multiple objects of same type.
- 4
Syntax : function identifier (parameter,...){ }
- 5 If the function is designed to use as a constructor than name of function should be upper camel case.
- 6 The list of parameter provided to the function will be treated as keys/properties of the object.
- 7 The argument pass when function is called will be value of object.
- 8 We can copy the values into the keys of the object from parameter using this keyword.
- 9 We can create a object using the constructor function with the help of new keyword.
- 10To create constructor function we will not use arrow function because they does not have 'this' keyword .
- 11Synatx : let variable = new function_name(arguments)
- 12
Example :
1function Car(model,color,engine) {2this.model = model;3this.color = color;4this.engine = engine;5}67let car1 = new Car(1021,"red","V8");8console.log(car1);9// { model:1021,color:"red",engine:"V8" }