有私人财产& ES6课程中的方法

时间:2016-01-19 08:13:35

标签: javascript class ecmascript-6

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

另外,我检查了这个帖子:Private properties in JavaScript ES6 classes并发现我们可以使用WeakMap来存储私人数据。这有点奇怪,但它仍然可以解决。我确实设法将它用于私人数据。

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

如果有人能够使用ES6类和私有方法重写这部分代码,我会很高兴能够向我展示 clean 方法。

感谢。

这是普通的旧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) {
        ...
    }
}

2 个答案:

答案 0 :(得分:13)

  

似乎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) {
            …
        };
    }
}

答案 1 :(得分:3)

您可以使用符号来提供一种私人成员。

const KEY = Symbol( 'key' )
const ANOTHER = Symbol( 'another' )

class Foo {
  constructor() {
    this[ KEY ] = 'private'
  }

  say() {
    console.log( this[ KEY ] )
  }

  [ ANOTHER ] = 'transpilation required'
}

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

相关问题