繁体   English   中英

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

[英]Returning ES6 Proxy from the ES6 class constructor

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

例如

var row = new Row({
  name : 'John Doe',
  email : 'uhiwarale@gmail.com'
}, Schema);

row可以有方法。 但是当用户尝试设置row.password ,不允许使用它们。

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

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

如果确定代理发生了,则限制设置功能的一种可能解决方案是返回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 : 'john@doe.com'
});

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

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

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

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

您可以在不使用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()页面上找到有关如何使用它的更多信息。

暂无
暂无

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

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