Javascript 如何在此类中生成全局分解表单?
例如,我试图在类中对此进行全局分解Javascript 如何在此类中生成全局分解表单?,javascript,Javascript,例如,我试图在类中对此进行全局分解 class Car { constructor( color, speed, type, ) { this.color = color; this.speed = speed; this.type = type; } method1() { const { color, speed, type } = this;
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;
}
}
不是在每个方法中对其进行分解,而是有一种方法可以将其作为所有方法的全局进行分解
在每个方法中,我只引用变量,而不是调用它。不,没有。如果要在每个方法中创建局部变量,则不能全局创建 唯一的替代方法是不使用
类
,而是使用工厂函数,该函数在构造函数参数上构建闭包:
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;
}
};
}
不,没有。如果要在每个方法中创建局部变量,则不能全局创建 唯一的替代方法是不使用
类
,而是使用工厂函数,该函数在构造函数参数上构建闭包:
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;
}
};
}
你为什么觉得有必要对它进行分解?在方法中需要该变量的任何地方,都可以使用
this.color
。为什么不使用this.color
?如果我在引用的每个变量中使用this
,这感觉像是多余和重复的。这就是为什么我要采用这种方法。另外,如果我有20个变量,并且我在每个函数或方法中使用它们,想象一下我每次在每个方法中使用这些变量时编写的重复代码,我的意思是全局解构是this
。。。您如何想象使用“全局解构”访问这些变量?就像在方法中只写color
,speed
等等因为作用域不是这样工作的。使用这个正是设计类成员访问的方式。因此,除了将变量移动到全局范围外(即,在Car
类之外,您将丢失有关哪个Car实例具有该颜色/类型/速度的信息)使用这些变量而不使用this
的唯一方法是按照您在问题中的建议对其进行分解。您为什么认为需要对其进行分解?在方法中需要该变量的任何地方,都可以使用this.color
。为什么不使用this.color
?如果我在引用的每个变量中使用this
,这感觉像是多余和重复的。这就是为什么我要采用这种方法。另外,如果我有20个变量,并且我在每个函数或方法中使用它们,想象一下我每次在每个方法中使用这些变量时编写的重复代码,我的意思是全局解构是this
。。。您如何想象使用“全局解构”访问这些变量?就像在方法中只写color
,speed
等等因为作用域不是这样工作的。使用这个正是设计类成员访问的方式。因此,除了将变量移动到全局范围外(即,在Car
类之外,您将丢失有关哪个Car实例具有该颜色/类型/速度的信息),使用这些变量而不使用的唯一方法是按照您在问题中的建议对其进行分解。