[code]class Variable { #value; #dependents = new Set(); constructor(value) { this.value = value; } get value() { return this.#value; } valueOf() { return this.value; } toString() { return String(this.value); } toNumber() { return Number(this.value); } set value(value) { if (this.#value === value) return; this.#value = value; var change = new WeakSet(); for (const dep of this.#dependents) dep.update(change); } register(dependent) { if (!(dependent instanceof Dependent)) throw new TypeError("Not a Dependent"); this.#dependents.add(dependent); } }
class Dependent extends Variable { constructor(variables, calculation) { super(); this.variables = variables; this.calculation = calculation; for (const variable of variables) { if (!(variable instanceof Variable)) throw new TypeError("Not a Variable"); variable.register(this); } this.calculate(); } update(change) { if (change.has(this)) throw new Error("Cyclic dependency"); change.add(this); this.calculate(); } calculate() { this.value = this.calculation(...this.variables); } }
var a = new Variable(1); var b = new Variable(1); var c = new Dependent([a, b], (a, b) => a + b); console.log(`${a} + ${b} = ${c}`); a.value++; console.log(`${a} + ${b} = ${c}`); a++; console.log(`${a} + ${b} = ${c}`);[/code]
Принуждение работает для A+B , но не удается для ++ < /код>. Почему?