js手札--js中new到底作了些啥

new的三个步骤

举个例子:函数

# 正常建立一个对象
function Super() {};
var s = new Super();

以上其实等价于3个步骤this

# 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

clipboard.png

3.初始化对象

# 把s当作Super中的this,作初始化s的操做
Super.call(s);
# 例如
function Super() {
  this.y = 1;
}

# 经过
Super.call(s);

# 其实就至关于
Super(_this) {
    _this.y = 1;
}
Super(s);

clipboard.png

相关文章
相关标签/搜索