我有以下 Javascript 类:
class App {
log_text(text) {
console.log(text)
}
process_response(response) {
this.log_text(response) // Uncaught TypeError: this.log_text is not a function
// self.log_text(response) // Uncaught TypeError: self.log_text is not a function
}
do_stuff() {
this.log_text('hello') // OK
}
fetch_data() {
jQuery.get('http://example.com/data/sample.txt', this.process_response, 'text')
}
}
当调用do_stuff
方法时,我可以通过调用this.log_text
访问log_text
。但是,在本例中用作 jQuery.get
的回调处理程序的方法 process_response
失败了,因为 this
代表了一个完全不同的该上下文中的对象。
同样,self.log_text
也会抛出 TypeError。
如本例所示,从 process_response
调用 log_text
的可能(或正确)方法是什么?
最佳答案
发生的事情是您正在传递您的 process_response 函数,仅此而已,因为您已经看到了此更改的上下文。一种解决方法是使用箭头语法包装它,这将在 jQuery 触发回调时保留 this 的值。
fetch_data() {
jQuery.get('http://example.com/data/sample.txt', (r)=> this.process_response(r), 'text')
}
关于javascript - 如何从用作回调的其他类方法访问方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54340134/