Effective JavaScript Item 39 绝不要重用父类型中的属性名
来源:互联网 发布:微信编辑器 知乎 编辑:程序博客网 时间:2024/06/07 01:46
本系列作为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属性覆盖了。
解决方案也很简单,在不同的类型中使用不同的属性名:
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;
总结
- 注意所有父类型中使用的属性名称不要和子类型中的重复。
- 在子类型中不要重用父类型中已经使用的属性名。
0 0
- Effective JavaScript Item 39 绝不要重用父类型中的属性名
- Effective JavaScript Item 47 绝不要向Object.prototype中添加可列举的(Enumerable)属性
- Effective JavaScript Item 32 绝不要修改__proto__
- Effective JavaScript Item 51 在类数组对象上重用数组方法
- Javascript中的属性类型
- Effective JavaScript Item 40 避免继承标准类型
- 读书笔记 effective c++ Item 9 绝不要在构造函数或者析构函数中调用虚函数
- 读书笔记 effective c++ Item 9 绝不要在构造函数或者析构函数中调用虚函数
- 读书笔记 effective c++ Item 9 绝不要在构造函数或者析构函数中调用虚函数
- 读书笔记 effective c++ Item 9 绝不要在构造函数或者析构函数中调用虚函数
- Effective JavaScript Item 29 避免使用非规范的Stack Inspection属性
- Effective JavaScript Item 46 优先使用数组而不是Object类型来表示有顺序的集合
- [翻译] Effective C++, 3rd Edition, Item 9: 绝不要在 construction(构造)或 destruction(析构)期间调用 virtual functions(虚拟函数)
- [翻译] Effective C++, 3rd Edition, Item 36: 绝不要重定义一个 inherited non-virtual function(通过继承得到的非虚拟函数)
- [翻译] Effective C++, 3rd Edition, Item 37: 绝不要重定义一个函数的 inherited default parameter value(通过继承得到的缺省参数值)
- Effective C++ Item 9 绝不在构造和析构过程中调用virtual函数
- Effective C++ Item 36 绝不重新定义继承而来的 non-virtual 函数
- Effective C++ Item 37 绝不重新定义继承而来的缺省参数值
- [版本]Git 少用 Pull 多用 Fetch 和 Merge
- 50 JS-4 创建对象 继承
- mini2440开发板移植mjpg-streamer
- 第七周项目3-简单分支问题体验(1)
- 程序员经典书籍
- Effective JavaScript Item 39 绝不要重用父类型中的属性名
- IT职场求生法则
- FreeRTOS 内存管理源码分析
- java.lang.OutOfMemoryError: PermGen space及其解决方法
- java面向对象(一) 了解面向对象
- 中水处理设备:中水回用设备处理设备处理方法简析
- Eclipse开发环境导入android sdk的sample中的源码
- 清除Eclipse工作空间历史
- 获取应用在ios系统通知中心的设置?开启:关闭