不要使用新的构造函数创建对象

Art*_*kyi 6 javascript

是否有选项不在构造函数中创建具有特定条件的对象,例如

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)

ktm*_*124 5

我认为你应该做的是抛出异常.

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)