S
S
Sergey2019-10-09 18:51:23
JavaScript
Sergey, 2019-10-09 18:51:23

Why is the class instance context lost?

Good afternoon. This question stems from another question . Here is the class code:

class Authorized {
    constructor() {
        this.jwt = require('jsonwebtoken')
        this.secretKey = 'dSjkLsSjerIfkL'
        
    }
    createSign(data, secretKey){
        console.log('create data', this)
        return this.jwt.sign(data,secretKey)
    }
    isAuthorized(req, res, next){
        console.log('isAuth',this)
        next()
}

I simplified it and added console.log(). The first createSign method is used as a function and this is valid for it. The second method is used as a middleware and this is undefined for it. Tell me why this is happening.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-10-09
@Banjamin

Because it is used as a middleware.
Call it by binding content, something like this

const Authorized = require('../moduls/authorized')
const auth = new Authorized();


// так
router.get("path/",auth.isAuthorized.bind(auth));
// или так
router.get("path/",(...a)=>auth.isAuthorized(...a));

and in a bunch of other ways
, you can read about Binding a context to a function,
isAuthorized(){
   return (req, res, next)=>{
      console.log('isAuth',this)
      // тут код мидлвара
  }
}

and use it like this
router.get("path/",auth.isAuthorized());
// или
router.post("path/",auth.isAuthorized());
// или
router.use(auth.isAuthorized());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question