… 항복하지 않는 방법
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();