tc39 / proposal-private-methods

Private methods and getter/setters for ES6 classes
https://arai-a.github.io/ecma262-compare/?pr=1668
345 stars 37 forks source link

[Proposal] Independent private field #12

Closed Aqours closed 6 years ago

Aqours commented 7 years ago

e.g: code

const logName = function () {
    console.log(private.name);
};

class A {

    name = 'public name';
    private name = 'private name';
    // private value = 'private value'; [1]

    constructor() {
        private.value = 'private value'; // like [1]
        private.logName(); // `private.` like `this.`, but cannot access by instance.
        logName.call(this); // 'private name'
    }

    private logName() {
        console.log(private.name);
    }

}

const a = new A();
console.log(a.name); // 'public name'
console.log(a.logName); // undefined
console.log(A.prototype.logName); // undefined

A.prototype.logName = function () {
    console.log(`${this.name} + ${private.name}`);
};
a.logName(); // 'public name + private name'
littledan commented 7 years ago

I don't know what you're getting at here.

claudepache commented 7 years ago

@Aqours If you can use the word private for accessing the private state of an instance of A outside of the lexical scope delimited by class A { /* ... */ }, ... it means that it is no longer private state.

Aqours commented 7 years ago

@claudepache We can modify the prototype of a class dynamically. I think private variable can be accessed by method in prototype, but cannot be accessed directly by property.

littledan commented 6 years ago

As @claudepache explained above, syntax based on private and . is not feasible for JavaScript.