Search code examples
javascriptclasssettergetterself

Javascript Getters and Setters on class itself


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


Solution

  • You can't.

    foo = 7;
    

    Will re-assign foo to 7.