js手札--js中new到底做了些啥
new的三个步骤
举个例子:
# 正常创建一个对象
function Super() {};
var s = new Super();
以上其实等价于3个步骤
# 3个步骤
var s = {};
s.__proto__ = Super.prototype;
Super.call(s);
# 注:1.2两步,其实就是Object.create(Super.prototype);
1.创建一个空对象{}
var s = {};
2.拷贝构造函数的prototype 给 实例对象的 proto
s.__proto__ === Super.prototype
3.初始化对象
# 把s当做Super中的this,做初始化s的操作
Super.call(s);
# 例如
function Super() {
this.y = 1;
}
# 通过
Super.call(s);
# 其实就相当于
Super(_this) {
_this.y = 1;
}
Super(s);