Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Getters and Setters on class itself [closed]

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'.

like image 572
Jrs.b Avatar asked Feb 04 '26 10:02

Jrs.b


1 Answers

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.

like image 64
tommybananas Avatar answered Feb 05 '26 22:02

tommybananas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!