例如,我试图在课堂上从中进行全局解构class Car { constructor( color, speed, type, ) { this.color = color; this.speed = speed; this.type = type; } method1() { const { color, speed, type } = this; // do something with speed, color, type; } method2() { const { color, speed, type } = this; // do another thing with speed, color, type; } method3() { const { color, speed, type } = this; // do another thing with speed, color, type; }}而不是在每个方法中解构 this 有没有办法将它作为所有方法的全局在每个方法中,我只是引用变量而不是调用它
1 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
不,那里没有。如果你想在每个方法中创建局部变量,你不能在全局范围内这样做。
唯一的选择是不使用 aclass而是使用在构造函数参数上构建闭包的工厂函数:
function Car(color, speed, type) {
return {
get color() { return color; },
get speed() { return speed; },
get type() { return type; },
method1() {
// do something with speed, color, type;
},
method2() {
// do another thing with speed, color, type;
},
method3() {
// do another thing with speed, color, type;
}
};
}
添加回答
举报
0/150
提交
取消