This question already has answers here:
How does the “this” keyword work?
                                
                                    (22个答案)
                                
                        
                        
                            How to access the correct `this` inside a callback?
                                
                                    (10个答案)
                                
                        
                                3年前关闭。
            
                    
为什么类在ExpressJS中的行为不同?例如:

使用expressJS

lib / Polygon.js:

class Polygon {

    log (req, res) {
        var publicKey = req.params.publicKey;
        var query = req.query;
        console.log(this); // undefined

        var output = {
            publicKey :publicKey,
            query: query
        };
        res.send(output);
    }
}

export {Polygon as default}


app.js:

import express from 'express';
import Polygon from './lib/Polygon';

var polygon = new Polygon();
app.get('/input/:publicKey', polygon.log);


没有expressJS

lib / Polygon.js:

class Polygon {
   log(req, res) {
        console.log(this); // Polygon {}
    }
}

export { Polygon as default}


app.js:

import Polygon from 'Polygon';

var p = new Polygon();

p.log('world')


如何在expressjs中获取未定义的console.log(this);返回Polygon {}

最佳答案

在第二个代码段中,log函数被称为p对象的成员,这就是this引用该对象的原因。在第一个代码段中,情况并非如此,因为您正在将该方法传递给另一个函数,并且该方法与对象分离。您可以使用this方法显式设置bind值:

app.get('/input/:publicKey', polygon.log.bind(polygon));

10-05 20:50
查看更多