When declaring a js class we can define the getters and setters for properties of that class like so:
class Foo{
get bar(){
return 'foo-bar';
}
set bar(n){
this.baz = n * 10;
}
}
let foo = new Foo();
console.log(foo.bar) //foo-bar
foo.bar = 7;
console.log(foo.baz) //70
What I was wondering is, how would I define getters and setters on the class itself? So that for example foo = 7 would trigger a block of code and console.log(foo) would print 'foo-bar'.
You can't. foo = means you are assigning a value to the variable foo. The best you can do is use a constructor to run some code when an instance of your class gets created.
class Foo{
constructor(){
console.log('A Foo instance has been created!');
}
get bar(){
return 'foo-bar';
}
set bar(n){
this.baz = n * 10;
}
}
Some languages also have a destructor specification whenever a value is destroyed or out of scope and eventually cleaned up by a garbage collector, etc, but es6 does not provide such functionality.
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