首页 > 解决方案 > 引用 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功能的所有字段?

标签: javascriptvue.js

解决方案


一种解决方案是将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)


推荐阅读