簡體   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