Effective JavaScript Item 39 绝不要重用父类型中的属性名

本系列作为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 alienID
	scene.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. 在子类型中不要重用父类型中已经使用的属性名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值