Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not to create an object with new Constructor

Tags:

javascript

Is there an option to not create an object with particular condition within constructor, e.g.

function Monster(name, hp) {
    if (hp < 1) {
       delete this;
    }
    else {
           this.name = name;
    }
}
var theMonster = new Monster("Sulley", -5); // undefined
like image 269
Artem Svirskyi Avatar asked Mar 12 '13 07:03

Artem Svirskyi


1 Answers

I think what you're supposed to do is throw an exception.

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);
like image 175
ktm5124 Avatar answered Oct 09 '22 18:10

ktm5124