Für… in nicht nachgebenden Methoden
Angesichts der folgenden:
export class MyClass {
public dataA = 0
private dataB = 123
public myMethod(): any {
return {
test: 'true'
}
}
constructor() {
for (const propOrMethod in this) {
console.log({propOrMethod})
}
}
}
const myInst = new MyClass()
Ich führe das mit ts-node index.ts
und alles was ich bekomme ist:
{ propOrMethod: 'dataA' }
{ propOrMethod: 'dataB' }
Ohne Bezug zu myMethod
. Ich würde gerne alle Methoden meiner Klasse durchlaufen, aber sie scheinen nicht zu existieren
Antworten
for..in
iteriert über alle aufzählbaren Eigenschaften der Instanz und entlang der Prototypenkette. Normale Methoden in einer Klasse sind jedoch nicht aufzählbar:
class MyClass {
myMethod() {
return {
test: 'true'
};
}
}
console.log(Object.getOwnPropertyDescriptor(MyClass.prototype, 'myMethod').enumerable);
Es wird also nicht wiederholt.
Wenn Sie auch über nicht aufzählbare Eigenschaften iterieren möchten, verwenden Sie Object.getOwnPropertyNames
(das über die eigenen Eigenschaftsnamen des Objekts iteriert. Sie müssen dies also rekursiv tun, wenn Sie alle Eigenschaftsnamen an einer beliebigen Stelle in der Prototypenkette möchten):
const recurseLog = obj => {
for (const name of Object.getOwnPropertyNames(obj)) {
console.log(name);
}
const proto = Object.getPrototypeOf(obj);
if (proto !== Object.prototype) recurseLog(proto);
};
class MyClass {
dataA = 0;
dataB = 123;
constructor() {
recurseLog(this);
}
myMethod() {
return {
test: 'true'
};
}
}
const myInst = new MyClass();
Sie können die Methode auch aufzählbar machen:
class MyClass {
dataA = 0;
dataB = 123;
constructor() {
for (const propOrMethod in this) {
console.log({propOrMethod})
}
}
myMethod() {
return {
test: 'true'
};
}
}
Object.defineProperty(MyClass.prototype, 'myMethod', { enumerable: true, value: MyClass.prototype.myMethod });
const myInst = new MyClass();
Oder weisen Sie die Methode nach der Klassendefinition zu:
class MyClass {
dataA = 0;
dataB = 123;
constructor() {
for (const propOrMethod in this) {
console.log({propOrMethod})
}
}
}
MyClass.prototype.myMethod = () => ({ test: 'true' });
const myInst = new MyClass();
Oder weisen Sie es der Instanz im Konstruktor zu:
class MyClass {
dataA = 0;
dataB = 123;
constructor() {
this.myMethod = this.myMethod;
for (const propOrMethod in this) {
console.log({propOrMethod})
}
}
myMethod() {
return {
test: 'true'
};
}
}
const myInst = new MyClass();