[Javascript] Private class properties in Javascript

In this lesson we will learn about how to define real private properties in javascript classes.

 

Before:

class Pasta {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }
}

const x = new Pasta('Rivioli');
console.log('Test');
console.log(x._name);
// You are able to change the _name
x._name = "Hello"

 

Now:

class Pasta {
    #name = '';
    constructor(name) {
        this.#name = name;
    }

    get name() {
        return this.#name;
    }
}

const x = new Pasta('Rivioli');
console.log('Test');
console.log(x.name);

If you were going to access or modify the '#name' directly, it will throw error.

console.log(x.#name); // error
x.#name = "new name" // error

 

posted @ 2020-03-26 18:29  Zhentiw  阅读(127)  评论(0编辑  收藏  举报