码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Private class properties in Javascript

时间:2020-03-26 19:21:39      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:learn   error   pre   about   ast   this   ble   eal   col   

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

标签:learn   error   pre   about   ast   this   ble   eal   col   

原文地址:https://www.cnblogs.com/Answer1215/p/12576397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!