我正在嘗試getter在 javascript 實體中獲取函式。
理想(偽):
class T {
internal values = a, b
getters = c, d
}
const getters = []
for (key in test) {
if (test[key] is getter)
getters.push(test[key])
}
getters.forEach(getter => (getter.bind(test))()) // calls c() and d()
我以為Object.getOwnPropertyDescriptors可以給我一個getter,但它沒有用。
我看到原型(如果我通過 制作實體class)有getters,但我無法訪問這些值。
我的代碼:
class Test {
constructor() {
this.a = 1;
this.b = 2;
}
get c() { return this.a; }
get d() { this.a this.b; }
}
const test = new Test();
Object.getOwnPropertyDescriptors(test.__proto__);
/*
Object { constructor: {…}, c: {…}, d: {…} }
c: Object { get: c(), enumerable: false, configurable: true, … }
constructor: Object { writable: true, enumerable: false, configurable: true, … }
d: Object { get: d(), enumerable: false, configurable: true, … }
*/
test.__proto__.c; // undefined
test.__proto__.c(); // Uncaught TypeError: test.__proto__.c is not a function
原型中有c,但我無法訪問這些值。
有沒有辦法得到這些getters?
如果我必須閱讀的鏈接存在,請注意我。謝謝你。
uj5u.com熱心網友回復:
您需要get從描述符中提取屬性然后使用它 - 如果您嘗試.c直接訪問該屬性,您將呼叫 getter(或 setter)。
class Test {
constructor() {
this.a = 1;
this.b = 2;
}
get c() { return this.a; }
get d() { this.a this.b; }
}
const test = new Test();
const testGetters = Object.values(Object.getOwnPropertyDescriptors(Object.getPrototypeOf(test)))
.filter(descriptor => descriptor.get)
.map(descriptor => descriptor.get);
console.log(testGetters);
console.log('Invoking getter manually:', testGetters[0].call(test));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484837.html
標籤:javascript 原型 吸气剂
