Arnas Pecelis
Arnas Pecelis

Reputation: 149

es6 class methods can't reach this instance

So I made a class and have no idea why I can't reach this instance inside one method.

So in my router I'm calling the method like this

import Emails from '../controllers/emails'
import router from 'express'
....
route.post('/', Emails.setupEmail)

so after calling POST method it calls setupEmail method but it crashes with the message:

TypeError: Cannot read property 'availableEmailTypes' of undefined

and the code of class:

class Emails {

constructor() {
    this.availableEmailTypes = ['registration', 'forgot-password', 'two-factor']
}

setupEmail(req, res) {
    if (!req.body.type || !req.body.type.include(this.availableEmailTypes)) {
        return res.status(422).send({ success: false, message: 'Invalid email type' })
    }

    switch (req.body.type) {
        case 'registration':
            break
    }
}

}

export default new Emails()

so the main question is why I can't reach array created on constructor?

Upvotes: 1

Views: 153

Answers (1)

Sergiu Paraschiv
Sergiu Paraschiv

Reputation: 10153

Because of this and how it's dynamically bound based on call-time context. When you call Emails.setupEmail, inside of it this won't be the Emails instance you export. Either use arrow functions to define your methods or bind(Emails) when you call it.

Upvotes: 2

Related Questions