說明
- 今天閱讀koa源碼時,遇到
Object.create
,感覺對這個概念有點生疏,于是打開了MDN進行重新梳理 - 傳送門
Object.create()
- 直接套用官網的栗子
const person = {isHuman: false,printIntroduction: function () {console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);}
}
const me = Object.create(person);
console.log(me);
- 上面解釋了
創建一個新對象,使用現有的對象來提供新創建的對象的__proto__
- 即做了2件事:
- 創建一個新對象.
- 把原對象的屬性和方法放在新對象的__proto__屬性中
好處
- 個人認為.解決了對象賦值的淺拷貝問題
- 由于javascript的對象類型是引用類型(《JavaScript高級程序設計》(第三版)),如果使用正常的賦值法,如下:
const me = person;
me.isHuman = true;
console.log(person.isHuman);
可以看到,我們對me的操作,直接影響到person了.
使用Object.create來實現類式繼承
- 先找到javascript中,類的繼承究竟做了哪些事情
- 假設現在有類Shape如下:
class Shape {constructor(x, y) {this.x = 0;this.y = 0;}moved(x, y){this.x += x;this.y += y;console.log('Shape moved');}
}
- 假設類Rectangle繼承Shape
class Rectangle extends Shape{constructor(x, y){super();}
}
const rect = new Rectangle();
const shape = new Shape();
console.log('rect', rect);
console.log('shape', shape);
- 將他們打印出來,查看繼承到底做了些什么事情
- 可以看到:
- Rectangle調用了Shape的constructor函數
- Rectangle原型的原型繼承了Shape的原型
- 先實現Shape類
function Shape (x, y) {this.x = 0;this.y = 0;
}
Shape.prototype.moved = function (x, y){this.x += x;ths.y += y;console.log('Shape moved');
}
const shape = new Shape();
console.log('shape', shape);
- 在Rectangle類中調用Shape并將作用域綁定到當前作用域,即可實現
this.x =0; this.y = y
function Rectangle (x, y) {Shape.apply(this);
}
const rect = new Rectangle();
console.log('rect');
現在有2個點沒有解決:
3. Rectangle沿著原型鏈的構造函數找不到Shape
4. moved方法沒有繼承
想到Object.create方法,是創建一個新對象,并把該對象的屬性和方法都掛在__proto__
屬性上,有如下繼承方案:
Rectangle.prototype = Object.create(Shape.prototype);
const rect = new Rectangle();
console.log('rect', rect);
可以看到,基本上繼承成功了,只是Rectangle的構造函數(constructor)丟了.只需要重新帶上即可
Rectangle.prototpe.constructor = Rectangle;
總結
- 如果想要某個對象繼承另外一個對象所有的屬性和方法,且新對象的操作不會影響到原來的對象.可以使用Object.create方式賦值.
- 當在某個對象上找不到方法是,會順著原型鏈(prototype, 瀏覽器顯示為
__proto__
)逐級尋找.