Adam Sassano
Adam Sassano

Reputation: 273

How can I use a static getter from a class and call an object and use the this keyword?

How can I use the static getter, z(), and call an object to use the this keyword?

I suppose the method static y() does do what I am looking for. But I'm like to figure out if I can make this work with an actual getter.

This is my code:

class test {
    constructor(x, y, z) {
        this._x = x;
        this._y = y;
        this._z = z;
    }
    static get str() { return 'Some predefined value'; } // I can use this static getter.
    get x() { return this._x; } // I can use this non-static getter on a class instance and use the this keyword (obviously).
    static y() { return this._y; } // I can use this static method on a class instance using the this keyword.
    static get z() { return this._z; } // How can I use this on class instances?.
}

const obj = new test(2, 3, 4);

console.log(test.str); // Use static getter from class.
console.log(Object.getPrototypeOf(obj).constructor.str);  // Use static getter from object instance.
console.log(obj.x); // Use non-static getter and use the this keyword.
console.log(test.y.call(obj));  // Use static method and use the this keyword.

Upvotes: 0

Views: 161

Answers (1)

georg
georg

Reputation: 214969

To invoke a getter indirectly, you can use Reflect.get (MDN) with the third argument set to "this" object. The third argument to Reflect.get is

the value of this provided for the call to target if a getter is encountered.

Example:

class test {
    constructor(x, y, z) {
        this._z = z;
    }

    static get z() {
        return this._z;
    }
}

const obj = new test(2, 3, 4);

result = Reflect.get(test, 'z', obj)
console.log(result)

(As a side note, I hope your question is pure curiosity and you're not going to use this in production code).

Upvotes: 2

Related Questions