在 ES6 类中具有私有属性和方法

Have private properties & methods in ES6 classes

本文关键字:属性 方法 ES6      更新时间:2023-09-26

我只是在尝试ES6,并希望将用常规javascript编写的代码的一部分重写为ES6。现在,我在尝试重写 ES6 类中的私有属性和方法时陷入困境。ES6 中的类似乎没有明确提供任何私有数据或方法。

另外,我检查了这个线程:JavaScript ES6类中的私有属性,发现我们可以使用WeakMap来存储私有数据。这有点奇怪,但它仍然可能是一种解决方法。我确实设法将其用于私人数据。

但是私人方法呢? 在 ES6 类中使用私有方法(甚至受保护的方法)的推荐方法是什么?

如果有人能向我展示一种使用 ES6 类和私有方法重写这部分代码的干净方法,我将不胜感激。

谢谢。

这是普通的旧JavaScript代码:

function Deferred() {
    // Private data
    var isPending;
    var handlers = {
        resolve: [],
        reject: [],
        notify: []
    };
    // Initialize the instance
    init();
    function init() {
        isPending = true;
        this.promise = new Promise(this);
    }
    // Public methods
    this.resolve = function(value) {
        trigger('resolve', value);
    };
    this.reject = function(reason) {
        trigger('reject', reason);
    };
    this.notify = function(value) {
        trigger('notify', value);
    };
    this.on = function(event, handler) {
        ...
    };
    // Private method
    function trigger (event, params) {
        ...
    }
}

ES6 中的类似乎没有明确提供任何私有数据或方法。

正确。class语法适用于具有原型方法的普通类。如果你想要私有变量,你可以像往常一样将它们放在构造函数中:

class Deferred {
    constructor() {
        // initialise private data
        var isPending = true;
        var handlers = {
            resolve: [],
            reject: [],
            notify: []
        };
        // Private method
        function trigger(event, params) {
            ...
        }
        // initialise public properties
        this.promise = new Promise(this);
        // and create privileged methods
        this.resolve = trigger.bind(null, 'resolve');
        this.reject = trigger.bind(null, 'reject');
        this.notify = trigger.bind(null, 'notify');
        this.on = function(event, handler) {
            …
        };
    }
}

您可以使用符号来提供某种私有成员。

const KEY = Symbol( 'key' )
const ANOTHER = Symbol( 'another' )
class Foo {
  constructor() {
    this[ KEY ] = 'private'
  }
  say() {
    console.log( this[ KEY ] )
  }
  [ ANOTHER ] = 'transpilation required'
}

第二个符号使用类字段添加到类中,这仅在提案中,需要转译才能在任何地方工作,但其余符号在节点和新浏览器中工作。