For ... in not yield 方法

For ... in not yielding methods

鉴于以下情况:

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。我想遍历 class 的所有方法,但它们似乎不存在

for..in 遍历实例的所有可枚举属性并向上遍历原型链。但是 class 中的普通方法不可枚举:

class MyClass {
    myMethod() {
        return {
            test: 'true'
        };
    }
}
console.log(Object.getOwnPropertyDescriptor(MyClass.prototype, 'myMethod').enumerable);

所以它不会被迭代。

如果您还想遍历不可枚举的属性,请使用 Object.getOwnPropertyNames(它遍历对象的 own 属性 名称,因此您如果您想要原型链中任何位置的所有 属性 名称,则需要递归执行此操作):

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定义之后赋值方法:

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();