是否有选项不在构造函数中创建具有特定条件的对象,例如
function Monster(name, hp) {
if (hp < 1) {
delete this;
}
else {
this.name = name;
}
}
var theMonster = new Monster("Sulley", -5); // undefined
Run Code Online (Sandbox Code Playgroud)
我认为你应该做的是抛出异常.
function Monster(name, hp) {
if (hp < 1) {
throw "health points cannot be less than 1";
}
this.hp = hp;
this.name = name;
}
var m = new Monster("Not a good monster", 0);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |