[Javascript] Private class properties in Javascript

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[Javascript] Private class properties in Javascript的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript 的新特性:类的 #private 字段

JavaScript 中的 private 和 public 这两个词到底有多保留

在 JavaScript 中解密 OAEP RSA(如 PHP 的 openssl_private_decrypt)

9.请写出PHP5权限控制修饰符

javaBeanjstlMVC模式

class composition