javascript - 引用 this 的 javascript 构造函数不会更新属性
问题描述
对于令人困惑的问题命名,我深表歉意,我对 javascript 中的构造函数特别陌生,不太清楚如何表达它,但这是我正在努力解决的问题。
我正在使用 Builder 概念(此处为构造函数)来创建一个对象并为其设置特定值,如下所示:
数据构建器.js
export class DataBuilder {
static getDefaultData() {
return new DataBuilder();
}
constructor() {
this.test = 'original';
this.data = {
title: `myTitle`,
meta: [
{
hid: "og:title",
name: "og:title",
property: "og:title",
content: `Would like some content here with ${this.test} in the middle of a string`,
},
]
}
}
setTestData(input) {
this.test = input;
return this;
}
build() {
return this.data;
}
}
我从我的 vue 组件中调用它
索引.vue
export default {
head() {
return DataBuilder.getDefaultData()
.setTestData("testing123")
.build();
},
}
在构建对象时,它显示this.test
已成功更新为testing123
. 但是,content
里面meta
没有更新,仍然显示content: original
。理想情况下,meta
/content
部分应该已更新为 show content: testing123
。
我有这个想法,this
变量不是“反应性”或在构造函数内部更新,所以我想知道解决这个问题的正确方法是什么。我需要在哪里更新具有特定set
功能的所有字段?
解决方案
一种解决方案是将data
设置移动到其中build()
,以便始终data
使用最新的字段值进行设置:
export class DataBuilder {
//...
build() {
this.data = {
title: `myTitle`,
meta: [
{
hid: 'og:title',
name: 'og:title',
property: 'og:title',
content: `Would like some content here with ${this.test} in the middle of a string`,
},
]
};
return this.data;
}
}
class DataBuilder {
static getDefaultData() {
return new DataBuilder();
}
constructor() {
this.test = 'original';
}
setTestData(input) {
this.test = input;
return this;
}
build() {
this.data = {
title: `myTitle`,
meta: [
{
hid: 'og:title',
name: 'og:title',
property: 'og:title',
content: `Would like some content here with ${this.test} in the middle of a string`,
},
]
};
return this.data;
}
}
const data = DataBuilder.getDefaultData().setTestData('foo').setTestData('bar').build()
console.log(data)
推荐阅读
- python - 如何使用 sklearn 的 SGDClassifier 返回前 N 个预测的准确率?
- php - 使用php生成站点的镜像
- php - 我可以使用什么查询来获取每个类别的子类别?
- c++ - 此代码后缀和前缀在一行c ++中的相同变量的输出背后的逻辑是什么
- java - 如何按数字顺序处理多个索引
- android - 更新功能在 PC 上始终有效,但在移动设备上不可用
- xcode - 故事板和“自 iOS 11.0 以来不推荐使用底部布局指南”警告
- c# - 从多对多 EF Core 实体在剃须刀页面中构建复选框列表
- excel - 基于多个标准的价值排名
- python - 如何从推文中删除主题标签和@提及?- 蟒蛇/熊猫