標籤:++ 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;
總結
- 注意全部父類型中使用的屬性名稱不要和子類型中的反覆。
- 在子類型中不要重用父類型中已經使用的屬性名稱。
Effective JavaScript Item 39 絕不要重用父類型中的屬性名稱