के लिए ... नहीं उपज तरीकों में
निम्नलिखित को देखते हुए:
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। मैं अपनी कक्षा के सभी तरीकों पर पुनरावृति करना चाहता हूं, लेकिन वे मौजूद नहीं हैं
जवाब
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();