0

I am describing properties in the constructor function but when I called the Server.request method in index.js its not showing properties at

console.log(this)

it outputs {} (empty object)

Constructor

function Server(){
  if(!(this instanceof Server)) return new Server()

  this.actions = { // accepted actions
    login: {
      post: [['email', 'username'], 'password']
    },
    register: {
      post: 'name,surname,password,email,haveLicence,licenceKey'.split(',')
    }
  }
}

Request function

Server.prototype.request = (req /* express request object */)=>{
  console.log(this) // {}
  return new Promise((r,j)=>{
    let action = (req.url.match(/[a-z\-]+/i) || [])[0]

    if(!action) return r([400, 'NoAction']);

    action = this.actions[action] // Cannot read property 'register' of undefined.
...
}
antzshrek
  • 6,622
  • 5
  • 25
  • 40
  • I have just added an example inspired to this question: https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch/47318407#47318407 – loretoparisi Nov 15 '17 at 22:29

1 Answers1

2

This is the nature of es6 arrow functions. They bind this differently.

Try:

Server.prototype.request = function(req) {
    console.log(this) // 
    // etc.
}

A simplified example:

function Server() {
  this.string = "hello"
}

Server.prototype.request = function(req) {
  return this.string
}
Server.prototype.request_arrow = (req) => {
  return this.string
}
var s = new Server()

console.log(s.request())
console.log(s.request_arrow())
Mark
  • 74,559
  • 4
  • 81
  • 117