有私人财产ES6类中的方法

有私人财产ES6类中的方法

本文介绍了有私人财产ES6类中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用ES6,并希望将一些以常规javascript编写的代码重写为ES6。而现在,我试图在ES6类中重写私有属性和方法时被卡住。看起来ES6中的类没有明确提供任何具有私有数据或方法的东西。

I'm just trying out ES6 and want to rewrite a part of code written in regular javascript to ES6. And now, I'm stuck while trying to re-write the private properties and methods in ES6 classes. It seems like classes in ES6 doesn't explicitly provide anything to have private data or methods.

另外,我检查了这个线程:,并发现我们可以使用来存储私人数据。这有点奇怪,但仍然可以做一个工作。我确实设法将其用于私人数据。

Also, I checked this thread: Private properties in JavaScript ES6 classes and found out that we could use WeakMap to store private data. Which is sort of weird but still it can be a work around. And I did manage to use it for private data.

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

But what about private methods? What is the recommended way to have private methods (or even protected methods) in ES6 classes?

如果有人可以向我显示一个干净的方式,可以使用ES6类和私有方法重写这部分代码。

I would appreciate if anyone can show me a clean way to rewrite this part of code using ES6 class along with the private methods.

谢谢。

以下是原始的JavaScript代码:

Here's the plain old javascript code:

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) {
        ...
    }
}


推荐答案

正确。 语法用于具有原型方法的普通类。如果你想要私有变量,那么你一直将它们放在构造函数中:

Correct. The class syntax is for normal classes with prototype methods. If you want private variables, you put them in the constructor as always:

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

这篇关于有私人财产ES6类中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:46