6

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
2
  • 2
    Why don´t you move your condition outside of your Monster function? You cannot use theMonster anyway if you don´t want it to be an object. You could add this.isMonster = (hp >= 1); to your Monster function. Commented Mar 12, 2013 at 7:58
  • 3
    is throwing an exception an option? Commented Mar 12, 2013 at 7:58

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

Comments

4

A function called as a constructor (with the new operator) will always return an instance unless it explicitly returns an object. You can therefore return an empty object, and use the instanceof operator to check what came back:

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

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

This behaviour is explained in the spec (13.2.2):

 8. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.

 9. If Type(result) is Object then return result.

 10. Return obj.

However, as others have pointed out, whether you should actually do this is questionable.

4 Comments

It is a programming error to create a Monster with negative health, why would you go out of your way to make it silent and undiscoverable until later with completely unrelated error messages. Throwing an exception is the only thing to do.
@Esailija - I didn't say I agreed with the approach, I just answered the question ("Is there an option to not create an object with particular condition within constructor?"). I have added a note to say that you probably shouldn't do this.
It's not an error if the monster is undead... if you know what I mean ;)
I agree an exception would be better, but +1 for the spec anyways
1

It does not make sense, you are trying to stop construction of an object during its construction phase. The better way would be to use something suggested by @Amberlamps or use something like factory pattern to create objects.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.