为什么课堂上的“this”未定义?

时间:2018-03-07 03:18:36

标签: javascript node.js

我试图理解为什么“这个”有时会在课堂上被定义,以及如何修复它。我已经阅读了其他答案,但我想我所要求的是一个解决方案。我阅读了很多开源代码,因为它有助于我学习。每当我看到一个类时,代码就会一直使用它。每当我尝试创建一个类并在回调函数中调用它时,它都是未定义的。我使用var = this作为解决方案,但它引起了一些问题,我认为这是我刚才应该想到的。

这是一个例子

class myClass {
     constructor(ping) {
        this.run()
        this.ping = ping
     }

     run() {
        console.log(this.ping)
        //This is defined here
        request({
           url: 'https://test.com',
           method: 'get'
           },
           function (err, res, body) {
             this.ran(body)
            //"ran" is not a function
        })
     }

     ran(body) {
        console.log(body)
     }
 }

感谢任何输入!

0 个答案:

没有答案