=>Sometimes we need to create many objects of the same type.
=>To create an object type we use an object constructor function.
=>It is considered good practice to name constructor functions with an upper-case first letter(const Person1{}).
*what is object type?
It is a template to create many similar objects.
for example;
const Person1 {
name :John,
age : 25
}
const Person2 {
name :Kumar,
age : 30
}
const Person3 {
name :Ravi,
age : 28
}
These all have the same template, like name, age, so in this case there is no need to create separate object, because all have same structure so we can use constructor function.
for example;
function Person (name,age){
this.name = name ;
this.age = age ;
}
const person1 = new Person("John",25);
const person2 = new Person("Kumar",30);
const person3 = new Person("Ravi",28);
In this case, what the advantage? We added so many Person in just one line, I did only one function that will apply all,
In this program, we have the word ' this ', why we use that, that is what we are going to learn now.
First, we know how to create properties in an object from outside,
example;
const Person3 {
name:Ravi,
}
//this Person3 object have not key of age so that what we are going to create //
Person3.age = 28;
That's it, here what was happened is we mentioned Person3 first then we will mention what is inside Person3 that is we should mention, and we pshould use dot betweeen parent and child, that's why have dot between Person3 and agePerson3.age).
Person3.age = 28; finally i put the value for age, if age key is already present in the Person3 object, the value will change, if not present, that key it will be created as a property.
NOW WE ARE GOING TO RELATE (this & person3.age)
*Person3 is replaced by 'this' simple,
*'this' is the representation of current callback .
const Person1 = new Person("John",25);
const Person2 = new Person("Kumar",30);
const Person3 = new Person("Ravi",28); these are all the callbacks.
First, our goal is to shorten the code, so we use this constructor function
ex;1
function Person (name,age){
this.name = name;
this.age = age;
}
const Person1 = new Person("John",25);
const Person2 = new Person("Kumar",30);
const Person3 = new Person("Ravi",28);
ex2;
Person1 {
name :John,
age : 25
}
Person2 {
name :Kumar,
age : 30
}
Person3 {
name :Ravi,
age : 28
}
example1 and example2 both are same but example1 increase by one line and example2 is increase by three line.
In this case three line may be feel short but when we have more than 10 or so many properties, then we have to write more than 10 or so many number of lines in example 2 ,
but still example1 will solve that in one line.
this.name , Person3.name, Person1.name, and Person2.name all are same.
but one, this.name = Person3.name, Person1.name, and Person2
EXPLANATION OF THIS LINE(this.name = name ;)
this.name is to create variable like Person3.name
=name => this name is parameter what hava function
=>function person (name,age){
Top comments (0)