用new操作符创建函数的过程发生了什么

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/daiqisi/article/details/78753401

用new操作符创建函数的过程发生了什么

例子:
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");

用new操作符创建构造函数Person的实例person1、person2的这个过程都经历了一些什么?

1.创建一个新对象

2.将构造函数的作用域赋给新对象(因此this就指向了这个新对象)

3.执行构造函数中的代码(为这个新对象添加属性)

4.返回新对象



希望我的入坑经验对你有所帮助,愿圣光与你同在

猜你喜欢

转载自blog.csdn.net/daiqisi/article/details/78753401