【问题标题】:How can I use a static getter from a class and call an object and use the this keyword?如何使用类中的静态 getter 并调用对象并使用 this 关键字?
【发布时间】:2021-03-21 20:16:55
【问题描述】:

如何使用静态 getter、z() 并调用对象以使用 this 关键字?

我想方法 static y() 确实可以满足我的要求。但我想知道我是否可以使用真正的吸气剂来完成这项工作。

这是我的代码:

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.

【问题讨论】:

  • Object.getOwnPropertyDescriptor(test, 'z').get.call(obj)
  • 这行得通!如果您将其发布为答案,我可以将其标记为解决方案。
  • @AdamSassano:实际上,刚刚发现了一个更好的方法。

标签: javascript class static this getter


【解决方案1】:

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

在遇到 getter 时为调用 target 提供的 this 值。

例子:

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)

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

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 2013-06-11
    • 2019-07-19
    相关资源
    最近更新 更多