我在一個函數中有兩個類,由于某種原因,第二個函數this沒有被正確識別。類是Emitter和Receiver。我試圖弄清楚為什么this這里沒有被正確拾取。該日志包含在以下代碼中:const chat = (messages) => { class Emitter { constructor(messages = []) { this.messages = messages; this.event = () => {}; } setEvent(fn) { this.event = fn; } trigger() { this.messages.forEach(message => this.event(message)); } } class Receiver { constructor() { this.messages = []; // this prints correctly here ---> Receiver { messages: [] } console.log('this ===> ', this) } ping(message) { console.log('this ===>', this) // this here prints the following this ===> Emitter { messages: [ 'Hi', 'Hola', 'Bonjour', 'Hi' ], event: [Function: ping] } this.messages.push(message); } } const myReceiver = new Receiver(); const myEmitter = new Emitter(messages); myEmitter.setEvent(myReceiver.ping); myEmitter.trigger(); return myReceiver.messages;};
當一個函數中有兩個類時會出現這個問題
慕碼人8056858
2022-06-05 17:07:18