Given that modern Javascript engines can better detect circular references, is the code below acceptable? If not, what would be the design pattern in Javascript to mitigate this?
class Validator {
constructor(elem) {
this._elem = elem;
}
validate() {
if (this._elem.value < 0) {
throw new Error('Value cannot be negative');
} else {
console.log('Value is valid');
}
}
}
class Parent {
constructor() {
this._validator = new Validator(this);
this._value = 0;
}
get value() {
return this._value;
}
set value(newVal) {
this._value = newVal;
}
validate() {
this._validator.validate();
}
}
and this has
p._validator._elem === p
Would passing in interfaces like the below code mitigate this
class Validator {
constructor(valueGetter) {
this._valueGetter = valueGetter;
}
validate() {
if (this._valueGetter() < 0) {
throw new Error('Value cannot be negative');
} else {
console.log('Value is valid');
}
}
}
class Parent {
constructor() {
this._validator = new Validator(()=> {return this.value});
this._value = 0;
}
get value() {
return this._value;
}
set value(newVal) {
this._value = newVal;
}
validate() {
this._validator.validate();
}
}
However, this too seems to mask the reference wrapped because the function passed into the Validator class has the reference to the Parent class.