Js constructor

1. What is a constructor

In JavaScript, functions called with the new keyword are called constructors, which usually start with a capital letter

2. Scenarios using constructors

Var p1 = {name:'Tom',age:'18',sex:' male '}; Var p2 = {name:'Jerry',age:'18',sex:' male '}; Var p3 = {name:'Speike',age:'20',sex:' male '}; Var p4 = {name:'Tyke',age:'8',sex:' male '}; , var p... = {... }Copy the code

Example: If we want to record the class member information, we create each classmate “object”, if the class size is the case, we need to repeat the write many times. This is where the advantages of the constructor come into play, and what we find is that each of the students has a name, age, and sex attribute, but each of them has its own value, so we pass in those attributes as arguments to the constructor, and we can create the following function.

function Person(name, age, sex) {
    this.name = name;
    this.age= age;
    this.sex= sex;
}
Copy the code

As with the above function, we can create an object using the new keyword, that is, the constructor.

Var p1 = new Person('Tom', '18', 'male '); Var p2 = new Person('Jerry', '18', 'male ');Copy the code

At this point, we find it very convenient to create objects that, in this scenario, generate a lot of repetitive code, which can be reused using constructors.

3. Constructor execution process

function Animal(color) {
 this.color = color;
}
Copy the code

The Animal function is not yet a constructor, it is only a constructor when called with the new keyword. As follows

var dog = new Animal("black");
Copy the code

Execution process:

Copy the code

At this point, the Person constructor does several things.

  1. When called with the new keyword, a new workspace is created, marked as an instance of Person
  2. Binds the stereotype of an empty object to the stereotype of the constructor following the new operator
  3. This inside the function body points to the memory and executes the constructor’s body, creating related properties and methods
  4. Check whether the result of execution returns a new object. If so, use the new object returned. If not, return the original object (obj).

We can draw the following conclusion

Var p1 = Person('Tom',' male ','18');Copy the code

Whenever an instance is created, a new memory space (p1) is created, and this inside the function body points to P1 when p1 is created

So if you add a property to this, you add a property to the instance.

Return this by default

Since this inside the function body refers to the newly created memory space, this is returned by default, which means that the memory space, p1, is returned by default. At this point, the memory space of P1 is accepted by the variable P1. So this variable p1, which holds the memory address p1, is marked as an instance of Person.

If no return value is manually added, this is returned by default

function Person() {
 this.name = 'Tom';
}

var p1 = new Person();
Copy the code