从ES6类构造函数返回ES6代理

问题描述 投票:13回答:2

我希望用户只为对象设置特定属性,但同时应该从自定义类构造该对象。

例如

var row = new Row({
  name : 'John Doe',
  email : '[email protected]'
}, Schema);

row可以有方法。但是当用户试图设置row.password时,他们是不允许的。

一种方法是使用new Proxy而不是new Row然后我们将放弃我们在Row类中所做的所有很酷的事情。我希望new Row返回一个代理对象,其中this引用作为代理目标。

有人对此有什么想法吗?如果你知道mongoosemongoose是怎么做的?

javascript proxy es6-class es6-proxy
2个回答
13
投票

如果确定代理发生了,则限制设置功能的一种可能解决方案是返回ES6代理实例。

默认情况下,javascript中的构造函数会自动返回this对象,但您可以通过将this上的代理实例化为目标来定义并返回自定义行为。请记住,代理中的set方法应返回一个布尔值。

MDN:set方法应该返回一个布尔值。返回true表示赋值成功。如果set方法返回false,并且赋值发生在strict-mode代码中,则抛出TypeError。

class Row {
  constructor(entry) {
    // some stuff

    return new Proxy(this, {
      set(target, name, value) {
        let setables = ['name', 'email'];
        if (!setables.includes(name)) {
          throw new Error(`Cannot set the ${name} property`);
        } else {
          target[name] = value;
          return true;
        }
      }
    });
  }

  get name() {
    return this._name;
  }
  set name(name) {
    this._name = name.trim();
  }
  get email() {
    return this._email;
  }
  set email(email) {
    this._email = email.trim();
  }
}

因此,现在不允许根据代理设置非setable属性。

let row = new Row({
  name : 'John Doe',
  email : '[email protected]'
});

row.password = 'blahblahblah'; // Error: Cannot set the password property

也可以在get方法上有自定义行为。

但是,请注意并注意覆盖返回到调用上下文的引用。

注意:示例代码已经在Node v8.1.3和现代浏览器上进行了测试。


8
投票

您可以在不使用Proxies的情况下执行此操作。

在类构造函数中,您可以像这样定义password属性:

constructor(options, schema) {
    this.name = options.name;
    this.email = options.email;
    Object.defineProperty(this, 'password', {
        configurable: false, // no re-configuring this.password
        enumerable: true, // this.password should show up in Object.keys(this)
        value: options.password, // set the value to options.password
        writable: false // no changing the value with this.password = ...
    });
    // whatever else you want to do with the Schema
}

您可以在MDN的Object.defineProperty()页面上找到有关如何使用它的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.