构造函数的执行流程
- 立刻创建一个新的对象。
- 将新建的对象设置为函数的this,在构造函数中可以使用this来引用新建的对象。
- 逐行执行函数中的代码。
- 将新建的对象作为返回值返回。
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);