如何使用 class 中的静态 getter 并调用对象并使用 this 关键字?

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

如何使用static getter, z(),调用对象使用this关键字?

我想 static y() 方法确实可以满足我的要求。但我想弄清楚我是否可以用实际的 getter.

来完成这项工作

这是我的代码:

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.

要间接调用 getter,您可以使用 Reflect.get (MDN) 并将第三个参数设置为“this”对象。 Reflect.get 的第三个参数是

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

示例:

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)

(作为旁注,我希望你的问题纯粹是出于好奇,你不会在生产代码中使用它)。