」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > JavaScript 中的陰影

JavaScript 中的陰影

發佈於2024-11-08
瀏覽:178

概述

JavaScript 中的一個特殊概念中的陰影,使得屬於父類別的方法可以在子類別中重新定義。

讓我們來看看兩款 21 世紀最受歡迎的遊戲,它們很容易猜到:GTA 和 Red Dead Redemption,除非您不喜歡開放世界遊戲。

Shadowing in JavaScript

回到我們的主題,我將讓 GTA 擔任父級角色,而 RDR 擔任子級角色。

程式碼

class GTA {
  constructor() {
    this.openWorld = {};
  }

  addFeature(feature, value) {
    this.openWorld[feature] = value;
    return this.openWorld[feature];
  }
}

class RDR extends GTA {
  addFeature(feature) {
    super.addFeature(feature, true);  // Calls the parent class' method and adds the feature
    return true;
  }
}

var role = new RDR();
console.log(role.addFeature('ROLE_PLAYER'));  // This will return true
console.log(role.openWorld);  // This will now have 'ROLE_PLAYER' added to it with value true

解釋:

super.addFeature(feature, true) 呼叫GTA類別中的addFeature方法,將feature加入openWorld物件中。

RDR中的addFeature方法傳回true,但它也確保ROLE_PLAYER被加入到openWorld物件中。

Shadowing in JavaScript

結束語

看起來 ROLE_PLAYER 剛進入野外開放世界,值為 true。希望他們已經準備好應對將遇到的錯誤——畢竟這是一款開放世界的遊戲!

版本聲明 本文轉載於:https://dev.to/alimalim77/shadowing-in-javascript-12ci?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3