简体   繁体   English

在JS中访问属性时如何抛出错误?

[英]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.

相关问题 访问属性但在对象中不存在时抛出错误 - throw error when attribute is accessed but doesn't exist in object 如何在属性更改时抛出错误? - How to throw an error when an attribute is changed? JScript:未加载图像时,如何抛出错误消息? - JScript: How can I throw an error message when image is not loaded? 启动expressjs服务器时如何抛出错误? - How can I throw an error when starting an expressjs server? 获取JS时如何抛出服务器错误 - How to throw a server error when fetching JS 如何创建 Error 的子类型来抛出它? - How can I create a subtype of Error to throw it? 如何访问组件的自定义属性? (角度5) - How can a custom attribute of a component be accessed? (Angular 5) 当我尝试为iframe src属性构建URL时,为什么AngularJS会抛出错误? - Why does AngularJS throw an error when I try to build a URL for an iframe src attribute? 当我取消注释一行代码时,会收到以下错误:_http_outgoing.js:359抛出新错误(“发送后无法设置标头。”); - When I uncomment one line of code, I receive this error: _http_outgoing.js:359 throw new Error('Can\'t set headers after they are sent.'); 在 Node 中使用 Multiparty 时,如何正确抛出错误? - When using Multiparty in Node, how do I properly throw an error?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM