1

I'd like to have an attribute throw an error if it's not defined, as in this question. Each of the answers to that question suggest using Python's @property decorator to raise an exception if the field isn't defined. How can I do that in JS?

EDIT:

I'm hoping for the equivalent of:

var MyObj = {
  method: function(){
    throw new Error('This method is not implemented');
  }
};

...but closer to:

var MyObj = {
  attribute: throw new Error('This attribute is not defined');
};
Community
  • 1
  • 1
yndolok
  • 5,197
  • 2
  • 42
  • 46

1 Answers1

3

This question can be broken down into two parts,

var myObj = {}; // just an example, could be a prototype, etc

How can I add a non-enumerable property to an Object?

This is done with Object.defineProperty

Object.defineProperty(myObj, 'foo', {get: function () {/* see next part */}});

I defined a getter, so you'll see the error message without needing to use () to invoke the function.

How can I throw an error?

This is as simple as using the throw statement. JavaScripts closest Error type to what you're looking for is most likely a ReferenceError.

throw new ReferenceError("Subclasses should implement this!");
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • I was trying to use your solution until I realized that ``Object.defineProperty`` doesn't work with IE < 9, which I unfortunately need to support. – yndolok May 28 '13 at 20:13
  • How far back do you need support for? I think IE8 might have `myObject.__defineGetter__` which you could use as a fallback (you'd have to check it does support it). This would mean it is enumerable but still works as a getter. If you want to go any further into the history books then you'll need a new way of looking up your properties (see [**here**](http://stackoverflow.com/a/6512201/1615483)) – Paul S. May 29 '13 at 20:09