What happens when a function is created with the new operator

What happens when a function is created with the new operator

example:
function CreatPerson(name,age,job){
        this.name = name;
        this.age = age;
        this.job = job;
        this.sayName = function(){
            console.log(this.name);
        }
    }

    var person1 = new Person("Nicholas",18,"Software Engineer");
    var person2 = new Person("Greg",27,"Doctor");

What happened in the process of using the new operator to create the instance person1 and person2 of the constructor Person?

1. Create a new object

2. Assign the scope of the constructor to the new object (so this points to the new object)

3. Execute the code in the constructor (add properties to this new object)

4. Return the new object



I hope my experience of entering the pit is helpful to you, may the Holy Light be with you

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324349340&siteId=291194637