日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

javascript --- Object.create的阅读

發布時間:2023/12/10 javascript 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 javascript --- Object.create的阅读 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

說明

  • 今天閱讀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__)逐級尋找.

    總結

    以上是生活随笔為你收集整理的javascript --- Object.create的阅读的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。