JavaScript构造函数的执行流程

构造函数的执行流程
  1. 立刻创建一个新的对象。
  2. 将新建的对象设置为函数的this,在构造函数中可以使用this来引用新建的对象。
  3. 逐行执行函数中的代码。
  4. 将新建的对象作为返回值返回。
function Person(name, age) {
    
    
    this.name = name;
    this.age = age;
    this.sayName = function () {
    
    
        console.log(this.name);
    }
}

var per = new Person("jack", 18);
var per2 = new Person("tom", 20);
var per3 = new Person("maly", 16);


// Person{name: "jack", age: 18, sayName: ƒ}
console.log(per);

// Person{name: "tom", age: 20, sayName: ƒ}
console.log(per2);

// Person{name: "maly", age: 16, sayName: ƒ}
console.log(per3);

猜你喜欢

转载自blog.csdn.net/weixin_43757001/article/details/114378150