JavaScript
现已支持在类里面创建私有属性
一、在过去我们是怎么做的?
通常是以一个特殊的变量命名, 来表示这是私有属性, 例如下面的 _name
class Person {
constructor() {
this._name = "张三";
}
}
const person1 = new Person();
console.log("person1: ", person1);
包括 vue
也是这么做的
如果对象里面某个属性是以 _ 开头的话, 从规范上来讲, 这个属性就是私有属性, 不想被外界使用, 只想在
类
的内部使用。
那我们能不能在外界使用呢?
答案是可以的, 这个属性只是名字特殊了一点, 却依然可以被外界使用
class Person {
constructor() {
this._name = "张三";
}
}
const person1 = new Person();
console.log("person1: ", person1);
console.log("person1._name: ", person1._name);
二、创建私有属性的方法
方法1: 使用 ES6
新增的 symbol
数据类型来创建私有属性
......
方法2: 在属性或方法前直接加 #
class Person {
#name; // <=================== 必须要在类中声明
constructor() {
this.#name = "张三";
}
#getName() {
return this.#name;
}
}
const person1 = new Person();
console.log(person1.#name); // <=================== 报错
console.log(person1.#getName()); // <=================== 报错
这里访问 person1.#name
、person1.#getName()
时, 就会报错
私有属性, 只能在类的内部访问
class Person {
#name; // 必须要在类中声明
constructor() {
this.#name = "张三";
}
#getName() {
return this.#name;
}
getName() {
return this.#getName(); // <=================== 私有属性, 只能在类的内部访问
}
}
const person1 = new Person();
// console.log(person1.#name);
// console.log(person1.#getName());
console.log(person1.getName());