如何重构对象属性的更新

How do I refactor the updating of object properties?

本文关键字:对象 属性 更新 重构 何重构      更新时间:2023-09-26

我有一个JavaScript对象,这些属性大多是静态的。它们可以在施工时确定。不过,我还添加了一个方法"变形",可以更改对象的状态。所以这些特性应该随之改变

我在下面成功地将其编码为一个方法(longNameMethod,没有问题(和一个属性(longNameProperty,有问题(。longNameProperty的问题在于构造函数和morph方法中的代码看起来非常相似。有没有办法消除这种重复?

var Fruit = function (name) {
    this.name = name;
    this.longNameMethod = function () {
        return this.name + this.name;
    }
    this.longNameProperty = this.name + this.name;
    this.morph = function(name) {
        this.name = name;
        // starting to feel redundant
        this.longNameProperty = this.name + this.name;
    }
    // update(); // hypothetical solution
};
var item = new Fruit('apple');
console.log(item.longNameMethod()); // apple apple
console.log(item.longNameProperty); // apple apple
item.morph('orange');
console.log(item.longNameMethod()); // orange orange
console.log(item.longNameProperty); // orange orange

我尝试包含一个"更新"方法来处理更新所有这些属性,但由于某种原因,我无法在构建过程中使用它。上面说这个名字没有定义。施工期间的操作顺序是什么?

编辑:是的,方法方法和属性方法在功能上与外部相同,但目标是使用属性方法。

编辑^2:所以我认为有多个问题在起作用。。。其中之一在这里解释:;这个";关键字在函数中工作?

当您将该方法分配到this:时,您需要在使用它之前添加该方法

var Fruit = function (name) {
    this.morph = function(name) {
        this.name = name;
        this.longNameProperty = this.name + this.name;
    }
    this.morph(name);
};
var item = new Fruit('apple');
console.log(item.longNameProperty); // apple apple
item.morph('orange');
console.log(item.longNameProperty); // orange orange