类中的私有属性用#来定义
class Animal{
//共有属性
name;
color;
//私有属性
#weight;
//构造方法
constructor(name,color,weight){
this.name = name;
this.color = color;
this.#weight = weight;
}
}
//实例化
const cat = new Animal('玲珑','white','5kg');
console.log(cat.name)
console.log(cat.color)
console.log(cat.#weight)
报错,可以看出,实例化对象不能访问类中的私有属性。
但是类中的方法可以访问,如下:
class Animal{
//共有属性
name;
color;
//私有属性
#weight;
//构造方法(必须使用关键字constructor)
constructor(name,color,weight){
this.name = name;
this.color = color;
this.#weight = weight;
}
info(){
console.log(this.name)
console.log(this.color)
console.log(this.#weight)
}
}
//实例化
const cat = new Animal('玲珑','white','5kg');
cat.info()
类的私有属性这个概念是在ES11中提出来的。