覆盖 class 的 属性 的 toString() - javascript

Override toString() of a property of a class - javascript

我正在尝试(重新)学习 javascript 中的 OOP。我想覆盖 object/class.
的 属性 数组的 toString 方法 This solution 适用于简单数组,但不适用于 object/class.
中的数组 我让它与 __proto__ 一起工作,但它似乎已被弃用。我不想覆盖 Array.toString,只覆盖 Solver.foo.toString。我可能遗漏了一些明显的东西。谢谢。

//solution that works on simple array
let version = [0, 3, 0];

version.toString = function() {
  return this.join('foo');
};

console.log("simple array: " + version);

//Same solution for my object/class
class Solver {
  constructor(arr) {
    this.foo = arr;
    this.foo.toString = function() {
      return this.join('foo');
    };
  };
}

//that works here
let bar = new Solver([0, 3, 0]);
console.log("property array: " + bar.foo);
//but not here
bar.foo = [0, 3, 0];
console.log("property array: " + bar.foo);

我建议您将 getters and setters 用于 JavaScript classes。使用 setter,一个简单的赋值就变成了对 class 的内部方法的调用,您可以利用它来始终确保您改变值以具有更新的 toString 函数。一个getter会帮你从外部调用价值。

这是一个工作示例:

class Solver {
    constructor(arr) {
        this.foo = arr;
    };
    
    set foo(arr) {
        this.fooValue = arr.slice(); // copying to avoid mutating the outside array
        this.fooValue.toString = function() {
            return this.join('foo');
        };
    }
    
    get foo() {
        return this.fooValue;
    }
}

let bar = new Solver([0, 3, 0]);
console.log("constructor property array: " + bar.foo);
const outsideArray = [0, 3, 1];
console.log("outside property array: " + outsideArray);
bar.foo = outsideArray;
console.log("setter property array: " + bar.foo);