Effective JavaScript Item 39 絕不要重用父類型中的屬性名稱

來源:互聯網
上載者:User

標籤:++   div   子類   rip   color   對象   nic   size   effect   

本系列作為Effective JavaScript的讀書筆記。

 

假設須要向Item 38中的Actor對象加入一個ID資訊:


function Actor(scene, x, y) {this.scene = scene;this.x = x;this.y = y;this.id = ++Actor.nextID;scene.register(this);}Actor.nextID = 0;

同一時候。也須要向Actor的子類型Alien中加入ID資訊:


function Alien(scene, x, y, direction, speed, strength) {Actor.call(this, scene, x, y);this.direction = direction;this.speed = speed;this.strength = strength;this.damage = 0;this.id = ++Alien.nextID; // conflicts with actor id!}Alien.nextID = 0;

在Alien的建構函式中,也對id屬性進行了賦值。因此。在Alien類型的執行個體中,id屬性永遠都是通過Alien.nextID進行賦值的。而不是Actor.nextID。

父類型的id屬性被子類型的id屬性覆蓋了。

 

解決方式也非常easy,在不同的類型中使用不同的屬性名稱:


function Actor(scene, x, y) {this.scene = scene;this.x = x;this.y = y;this.actorID = ++Actor.nextID; // distinct from alienIDscene.register(this);}Actor.nextID = 0;function Alien(scene, x, y, direction, speed, strength) {Actor.call(this, scene, x, y);this.direction = direction;this.speed = speed;this.strength = strength;this.damage = 0;this.alienID = ++Alien.nextID; // distinct from actorID}Alien.nextID = 0;

總結

  1. 注意全部父類型中使用的屬性名稱不要和子類型中的反覆。
  2. 在子類型中不要重用父類型中已經使用的屬性名稱。


Effective JavaScript Item 39 絕不要重用父類型中的屬性名稱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.