构建器模式不向对象添加值
Builder pattern not adding values to the object
我正在尝试遵循 ES6 Builder pattern,因为我现在开始构建一个更复杂的对象。
到目前为止我有:
class Opinion {
constructor () {
this.nuts = '';
}
}
class Builder {
constructor () {
this.opinion = new Opinion();
}
withNuts (nuts) {
this.nuts = nuts;
return this;
}
build () {
return this.opinion;
}
}
export default Builder;
使用的是:
import Builder from '../helpers/builder/opinion';
const defaultOpinion = new Builder()
.withNuts(2.9)
.build();
输出:
opinion: {"nuts":""}
为什么它没有内置到对象中?
此外,当我想将一个对象传回 Builder 进行编辑时,它也会 returns 空白(这是有道理的),但我当前的 Builder 设置是否允许这样做?例如:
const opinionChange = new Builder(defaultOpinion)
.withNuts(0.8)
.build();
非常感谢您的帮助。
您错过了对 this.opinion.nuts
的赋值,而是在对象上创建了自己的 属性 nuts
。替换为这个
withNuts (nuts) {
this.opinion.nuts = nuts;
return this;
}
工作代码
class Opinion {
constructor () {
this.nuts = '';
}
}
class Builder {
constructor () {
this.opinion = new Opinion();
}
withNuts (nuts) {
this.opinion.nuts = nuts; // this.opinion.nuts
return this;
}
build () {
return this.opinion;
}
}
const defaultOpinion = new Builder()
.withNuts(2.9)
.build();
console.log(defaultOpinion);
withNuts
方法应该更新 this.opinion.nuts
而不是 this.nuts
:
withNuts (nuts) {
this.opinion.nuts = nuts;
return this;
}
我正在尝试遵循 ES6 Builder pattern,因为我现在开始构建一个更复杂的对象。
到目前为止我有:
class Opinion {
constructor () {
this.nuts = '';
}
}
class Builder {
constructor () {
this.opinion = new Opinion();
}
withNuts (nuts) {
this.nuts = nuts;
return this;
}
build () {
return this.opinion;
}
}
export default Builder;
使用的是:
import Builder from '../helpers/builder/opinion';
const defaultOpinion = new Builder()
.withNuts(2.9)
.build();
输出:
opinion: {"nuts":""}
为什么它没有内置到对象中?
此外,当我想将一个对象传回 Builder 进行编辑时,它也会 returns 空白(这是有道理的),但我当前的 Builder 设置是否允许这样做?例如:
const opinionChange = new Builder(defaultOpinion)
.withNuts(0.8)
.build();
非常感谢您的帮助。
您错过了对 this.opinion.nuts
的赋值,而是在对象上创建了自己的 属性 nuts
。替换为这个
withNuts (nuts) {
this.opinion.nuts = nuts;
return this;
}
工作代码
class Opinion {
constructor () {
this.nuts = '';
}
}
class Builder {
constructor () {
this.opinion = new Opinion();
}
withNuts (nuts) {
this.opinion.nuts = nuts; // this.opinion.nuts
return this;
}
build () {
return this.opinion;
}
}
const defaultOpinion = new Builder()
.withNuts(2.9)
.build();
console.log(defaultOpinion);
withNuts
方法应该更新 this.opinion.nuts
而不是 this.nuts
:
withNuts (nuts) {
this.opinion.nuts = nuts;
return this;
}