…メソッドを生成しない場合
Nov 23 2020
次の場合:
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()
私はこれを実行しts-node index.ts
、私が得るのは:
{ propOrMethod: 'dataA' }
{ propOrMethod: 'dataB' }
を参照せずにmyMethod
。クラスのすべてのメソッドを繰り返し処理したいのですが、存在しないようです
回答
2 CertainPerformance Nov 24 2020 at 04:37
for..in
インスタンスの列挙可能なすべてのプロパティを繰り返し、プロトタイプチェーンを上っていきます。ただし、クラス内の通常のメソッドは列挙できません。
class MyClass {
myMethod() {
return {
test: 'true'
};
}
}
console.log(Object.getOwnPropertyDescriptor(MyClass.prototype, 'myMethod').enumerable);
したがって、それは繰り返されません。
列挙できないプロパティもObject.getOwnPropertyNames
反復処理する場合は、次を使用します(オブジェクト自体のプロパティ名を反復処理するため、プロトタイプチェーンの任意の場所にすべてのプロパティ名が必要な場合は、再帰的に実行する必要があります)。
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();
メソッドを列挙可能にすることもできます。
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();
または、クラス定義の後にメソッドを割り当てます。
class MyClass {
dataA = 0;
dataB = 123;
constructor() {
for (const propOrMethod in this) {
console.log({propOrMethod})
}
}
}
MyClass.prototype.myMethod = () => ({ test: 'true' });
const myInst = new MyClass();
または、コンストラクターでインスタンスに割り当てます。
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();