2

Is there anyway to make setter/getter only for class object? What I mean is, is there anyway to set get/set for this in class? For example:

class something {
    constructor() {
        // ...
    }
    get this() {
      return 'Fizz buzz'
    }
}

const somethingelse = new something
console.log(something) // "Fizz buzz"

This is what I want to get. If I want it to work exactly the same, I need to do const {this} = new something, which is what I don't want to use.

2 Answers2

1

No, there are no setters/getters for whole objects. A setter/getter always is a property. You assign/evaluate a reference to a property or variable, the object itself is not involved in that. You can't have an object that behaves like a primitive string when accessed. The closest you will get is something like

class Something {
    valueOf() {
        return 'Fizz buzz';
    }
}

const somethingelse = new Something;
console.log(something.valueOf()); // "Fizz buzz"
console.log(String(something)); // "Fizz buzz"
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

first of all, any reserved variable should not be overridden. So what you try to do is bad practice.

How does the "this" keyword work?

But if you want the this to point to a different scope you can easily do that locally with the call / apply functions or permanently with bind function.

Bogdan M.
  • 2,033
  • 6
  • 29
  • 48