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

相關文章
相關標籤/搜索