6

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

function Monster(name, hp) {
    if (hp < 1) {
       delete this;
    }
    else {
           this.name = name;
    }
}
var theMonster = new Monster("Sulley", -5); // undefined
4

3 回答 3

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);
于 2013-03-12T07:59:00.947 回答
4

被称为构造函数(带有new运算符)的函数将始终返回一个实例,除非它显式返回一个对象。因此,您可以返回一个空对象,并使用instanceof运算符检查返回的内容:

function Monster(name, hp) {
    if (hp < 1) {
       return {};
    }
    else {
       this.name = name;
    }
}
var theMonster = new Monster("Sulley", -5);

console.log(theMonster instanceof Monster); // false

规范( 13.2.2 )中解释了这种行为:

 8. 令result为调用 F 的 [[Call]] 内部属性的结果,提供 obj 作为 this 值,并提供传递给 [[Construct]] 的参数列表作为args

 9.如果 Type(result) 是 Object 则返回 result

 10. 返回对象。

但是,正如其他人指出的那样,您是否真的应该这样做是值得怀疑的。

于 2013-03-12T07:59:59.213 回答
1

这是没有意义的,您试图在对象的构造阶段停止构造对象。更好的方法是使用@Amberlamps 建议的东西或使用工厂模式之类的东西来创建对象。

于 2013-03-12T08:01:43.697 回答