在 Javascript 中重构为 class 时,我应该如何 const inside 函数
How should I const inside function when refactoring to class in Javascript
假设我有一个函数用作 class:
function Builder() {
const a = somethingThatReturnsAnArray();
this.b = somethingThatReturnsAnotherArray();
this.foo = () => {
a.push('test');
this.b.push('test');
}
}
// Later...
const builder = new Builder();
builder.foo();
将 a
声明为 const 与将 b
附加到 this
之间有什么区别吗?我可以将此函数转换为下面的 class 吗?
class Builder {
constructor() {
this.a = somethingThatReturnsAnArray();
this.b = somethingThatReturnsAnotherArray();
}
foo() {
this.a.push('test');
this.b.push('test');
}
}
如果是,在将所有内容转换为 class 属性时是否有一些注意事项?
我想将 const b = ...
转换为 this.b
会有一些陷阱,但我不确定。这样做的正确方法是什么?换句话说,在 Javascript 中重构为 class 时,我应该如何 const inside 函数?
a
在 class 中应该是私有的。
class Builder {
#a = somethingThatReturnsAnArray();
constructor() {
this.b = somethingThatReturnsAnotherArray();
}
foo() {
this.#a.push('test');
this.b.push('test');
}
}
假设我有一个函数用作 class:
function Builder() {
const a = somethingThatReturnsAnArray();
this.b = somethingThatReturnsAnotherArray();
this.foo = () => {
a.push('test');
this.b.push('test');
}
}
// Later...
const builder = new Builder();
builder.foo();
将 a
声明为 const 与将 b
附加到 this
之间有什么区别吗?我可以将此函数转换为下面的 class 吗?
class Builder {
constructor() {
this.a = somethingThatReturnsAnArray();
this.b = somethingThatReturnsAnotherArray();
}
foo() {
this.a.push('test');
this.b.push('test');
}
}
如果是,在将所有内容转换为 class 属性时是否有一些注意事项?
我想将 const b = ...
转换为 this.b
会有一些陷阱,但我不确定。这样做的正确方法是什么?换句话说,在 Javascript 中重构为 class 时,我应该如何 const inside 函数?
a
在 class 中应该是私有的。
class Builder {
#a = somethingThatReturnsAnArray();
constructor() {
this.b = somethingThatReturnsAnotherArray();
}
foo() {
this.#a.push('test');
this.b.push('test');
}
}