For ... In Not Yielding Methods
Given the following: export class MyClass { public dataA = 0 private dataB = 123 public myMethod(): any { return { test: 'true' } }
Solution 1:
for..in
iterates over all enumerable properties of the instance and up the prototype chain. But normal methods in a class are not enumerable:
classMyClass {
myMethod() {
return {
test: 'true'
};
}
}
console.log(Object.getOwnPropertyDescriptor(MyClass.prototype, 'myMethod').enumerable);
So it doesn't get iterated over.
If you want to iterate over non-enumerable properties as well, use Object.getOwnPropertyNames
(which iterates over the object's own property names, so you'll need to do so recursively if you want all property names anywhere in the prototype chain):
constrecurseLog = obj => {
for (const name ofObject.getOwnPropertyNames(obj)) {
console.log(name);
}
const proto = Object.getPrototypeOf(obj);
if (proto !== Object.prototype) recurseLog(proto);
};
classMyClass {
dataA = 0;
dataB = 123;
constructor() {
recurseLog(this);
}
myMethod() {
return {
test: 'true'
};
}
}
const myInst = newMyClass();
You could also make the method enumerable:
classMyClass {
dataA = 0;
dataB = 123;
constructor() {
for (const propOrMethod inthis) {
console.log({propOrMethod})
}
}
myMethod() {
return {
test: 'true'
};
}
}
Object.defineProperty(MyClass.prototype, 'myMethod', { enumerable: true, value: MyClass.prototype.myMethod });
const myInst = newMyClass();
Or assign the method after the class definition:
classMyClass {
dataA = 0;
dataB = 123;
constructor() {
for (const propOrMethod inthis) {
console.log({propOrMethod})
}
}
}
MyClass.prototype.myMethod = () => ({ test: 'true' });
const myInst = newMyClass();
Or assign it to the instance in the constructor:
classMyClass {
dataA = 0;
dataB = 123;
constructor() {
this.myMethod = this.myMethod;
for (const propOrMethod inthis) {
console.log({propOrMethod})
}
}
myMethod() {
return {
test: 'true'
};
}
}
const myInst = newMyClass();
Post a Comment for "For ... In Not Yielding Methods"