从ES6类构造函数返回ES6代理 [英] Returning ES6 Proxy from the ES6 class constructor

查看:94
本文介绍了从ES6类构造函数返回ES6代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want user to only set specific properties to an object but as the same time that object should be constructed from custom class.

例如

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

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

row can have methods. But when user is trying to set row.password, they are not allowed.

一种方法是使用新代理而不是新行,但是随后我们将放弃我们在行类。我希望新行返回一个具有引用作为代理目标的代理对象。

One way to do it is using new Proxy instead of new Row but then we will loose all cool things we are doing inside Row class. I want new Row to return a proxy object with this reference as a target of proxy.

有人对此有任何想法吗?如果您知道猫鼬猫鼬怎么做?

Anybody have any ideas on this? If you know mongoose, how mongoose is doing it?

推荐答案

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

If the proxy is certain to happen for you, one possible solution to limit the set functionality is returning an ES6 Proxy instance.

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

By default, the constructor in javascript returns this object automatically but you could define and return a custom behavior by instantiating a proxy on this as a target. Keep in mind that the set method in proxy should return a boolean value.


MDN :set方法应返回布尔值。返回true表示
分配成功。如果set方法返回false,并且
分配发生在严格模式代码中,则将引发TypeError。

MDN: The set method should return a boolean value. Return true to indicate that assignment succeeded. If the set method returns false, and the assignment happened in strict-mode code, a TypeError will be thrown.



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();
  }
}

因此,现在不允许您将非

So, now you are not allowed to set the non-setable properties according to the proxy.

let row = new Row({
  name : 'John Doe',
  email : 'john@doe.com'
});

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

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

It's also possible to have s custom behavior on get method too.

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

However, beware and take care of overriding the reference that is returned to the calling context.

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

Note: The sample code has been tested on Node v8.1.3 and modern browsers.

这篇关于从ES6类构造函数返回ES6代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆