Let's say I have a class defined as follows:
class MyClass {
constructor (a) {
this.a = a;
}
_onPropertyChanged() {
// do something
}
}
Whenever the property "a" of an instance of MyClass changes, I want to trigger the _onPropertyChanged method on that instance. What is the best (most performant) way to achieve this using ECMAscript 6?
Classes create objects through the new operator. Each object has some properties (data or method) added by the class. The class stores some properties (data or method) itself, which are usually used to interact with instances.
There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.
There's no 'best' way, and the actual approach always depends on the final goal.
In its simplistic (and performant enough) form it is:
class MyClass {
constructor (a) {
this.a = a;
}
get a() {
return this._a;
}
set a(val) {
this._a = val;
this._onPropertyChanged('a', val);
}
_onPropertyChanged(propName, val) {
// do something
}
}
This is a simple example of what you can do for this situation and for a single property.
class MyClass {
constructor (a) {
this._a = a;
}
set a(value) {
let hasChanged = (this._a !== value);
this._a = value;
//Assumes value is primitive. Customize for objects
if(hasChanged) this._onPropertyChanged();
}
_onPropertyChanged() {
// do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With