先来看一个栗子:
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person("constRen", 28)
是不是不明白?没关系,我们接着往下看
原理(也就是 new 的过程发生了什么):
- 当
new关键字调用时,会创建一个新的内存空间 (创建一个空对象) - 函数体内部的
this指向该内存 (this指向这个空对象) - 执行函数体内的代码(为这个新对象添加属性)
- 返回新对象
拆解开来就是这样的
1、创建一个空对象( new 帮你做了)
var obj = new Object()
2、让 Person 中的 this 指向 obj(new 会帮你做,还帮你设置原型链,将 obj 的 __proto__ 成员指向了 Person 函数对象的 prototype ;new 为了知道原型在哪,所以指定原型的名字为 prototype )
var result = Person.call(obj)
obj.__proto__ = Person.prototype
3、并执行 Person 的函数体。
this.name = name;
this.age = age;
4、返回新对象 ( new 会帮你做)
return obj
等同于: 上面的 new 帮忙做了
function Student(name, chengji) {
console.log('this', this); // 这个this的指向 现在都会了吧?
this.name = name;
this.chengji = chengji;
this.go = function () {
console.log('this1', this); // 这儿也会了吧?
console.log('姓名:' + this.name + ' 成绩:' + this.chengji);
}
}
let std1 = new Student('狂徒张三', 98);
let std2 = new Student('背锅李四', 70);
std1.go();
std2.go();