@babel/plugin-proposal-private-methods中babel中配置,示例代码
时间: 2023-07-14 11:12:38 浏览: 176
在使用@babel/plugin-proposal-private-methods之前,需要安装@babel/core和@babel/plugin-proposal-class-properties这两个依赖。
安装命令如下:
```
npm install --save-dev @babel/core @babel/plugin-proposal-class-properties @babel/plugin-proposal-private-methods
```
然后在babel配置文件中指定插件即可。例如在babel.config.js中配置:
```javascript
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current"
}
}
]
],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-private-methods"
]
};
```
示例代码:
```javascript
class Person {
#name = '张三'; // 私有属性
#age = 18; // 私有属性
#showInfo() { // 私有方法
console.log(`姓名:${this.#name},年龄:${this.#age}`);
}
getName() { // 公有方法
return this.#name;
}
setName(name) { // 公有方法
this.#name = name;
}
getAge() { // 公有方法
return this.#age;
}
setAge(age) { // 公有方法
this.#age = age;
}
show() { // 公有方法
this.#showInfo();
}
}
const person = new Person();
person.show(); // 输出:姓名:张三,年龄:18
person.setName('李四');
person.setAge(20);
console.log(person.getName()); // 输出:李四
console.log(person.getAge()); // 输出:20
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)