简体   繁体   English

将javascript类实例限制为特定属性

[英]Restrict javascript class instances to particular properties

I would like to define the structure of a class, and throw an error if the user attempts to set a property on one of my object instances using a property that is not defined in the class. 我想定义一个类的结构,如果用户试图使用未在类中定义的属性在我的一个对象实例上设置属性,则抛出一个错误。

For example, say I have the following class: 例如,假设我有以下课程:

class MyClass {
  constructor() {
    this.propertyA = 'A value';
    this.propertyB = 'Another value';
  }
}

And then when the user is modifying object instances... 然后当用户修改对象实例时......

let myInstance = new MyClass();
myInstance.propertyA = 'a new value'; // would work fine
myInstance.propertyC = 'unknown property value'; // throw exception

Is this possible? 这可能吗? The seal keyword appears to be close to what I want. 密封关键字似乎接近我想要的。 It would prevent new properties from being added, but I would like to throw exceptions in case the user type-o's the valid property names. 它会阻止添加新属性,但我想在用户输入-o是有效属性名称时抛出异常。

Update: Using Object.preventExtensions , Object.seal , or Object.freeze in strict mode will cause errors when a non-existent property is assigned to an object. 更新:在严格模式下使用Object.preventExtensionsObject.sealObject.freeze在将不存在的属性分配给对象时导致错误。

You can use a Proxy to intercept new property additions and prevent new properties from being defined: 您可以使用Proxy拦截新属性添加并阻止定义新属性:

 class MyClass { constructor() { this.propertyA = 'A value'; this.propertyB = 'Another value'; return new Proxy(this, { get: (_, prop) => this[prop], set: (_, prop, value) => { if (!(prop in this)) throw new Error('Prop does not exist!'); this[prop] = value; } }); } } let myInstance = new MyClass(); myInstance.propertyA = 'a new value'; // would work fine console.log('about to set propertyC:'); myInstance.propertyC = 'unknown property value'; // throw exception 

A much terser method that prevents new properties from being added is to use Object.preventExtensions() . 防止添加新属性的更多方法是使用Object.preventExtensions() Attempts to add new properties will throw an error in strict mode: 尝试添加新属性将在严格模式下抛出错误:

 'use strict'; class MyClass { constructor() { this.propertyA = 'A value'; this.propertyB = 'Another value'; Object.preventExtensions(this); } } let myInstance = new MyClass(); myInstance.propertyA = 'a new value'; console.log('About to add propertyC'); myInstance.propertyC = 'unknown property value'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM