[英]How can I throw an error when an attribute is accessed in JS?
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. 该问题的每个答案建议使用Python的
@property
装饰器在未定义字段时引发异常。 How can I do that in JS? 我怎么能在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');
};
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 ? 如何向Object添加不可枚举的属性?
This is done with Object.defineProperty
这是通过
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. 我定义了一个getter ,因此您将看到错误消息,而无需使用
()
来调用该函数。
How can I throw an error? 我怎么能抛出错误?
This is as simple as using the throw
statement. 这与使用
throw
语句一样简单。 JavaScripts closest Error type to what you're looking for is most likely a ReferenceError . JavaScripts最接近您正在寻找的错误类型很可能是ReferenceError 。
throw new ReferenceError("Subclasses should implement this!");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.