【发布时间】: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