2

This is probably something a very small problem but I can't find its solution so please bear with me!

I don't understand why at const body = ctx.request.body ctx becomes undefined. Before it carried over this from the create() function which calls createEntity().

What am I doing wrong?

I'm calling a function createEntitylike this:

module.exports = {
  createEntity: () => {
    var ctx = this  // both ctx and this are fine
    return new Promise((resolve, reject) => {
      const body = ctx.request.body  // <-- ctx is undefined
      resolve();
    })
  }
}

create() calls createEntity(). It is a generator function wrapped with co()via Koa.js

create: function * () {
    this.body = yield createEntity.call(this)
}

EDIT: Here's a screenshot why I thought this is fine after calling createEntity: enter image description here

Hedge
  • 16,142
  • 42
  • 141
  • 246

2 Answers2

4

both ctx and this are fine

I doubt that. You are using an arrow function. You cannot set an arrow function's this via call because an arrow doesn't have an own this 1.

Use a normal function instead.

See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?


1: this inside createEntity refers to the top-level this of the module, which is module.exports:

this;        // <------------|
module.exports = {           |
  createEntity: () => {      |
    var ctx = this     // ---|
  }
}
console.log(this === module.exports); // true
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Yeah that was a dumb mistake. Please check out my screenshot in the original question why I thought `this` was fine. – Hedge Jul 28 '16 at 16:29
  • Object doesn't mean they are the same. If you have var object = {} it is also an Object but has nothing inside – LuisPinto Jul 28 '16 at 16:31
1

By assigning an arrow function to createEntity, this inside the arrow function is assigned to the value of this in the scope where the arrow function was declared, which is probably the global object (therefore if you're using use strict, this will be undefined), and it'll stay that way even if you invoke the function using call.

Use a common function expression instead

createEntity: function () {
    ...
}
Marco Scabbiolo
  • 7,203
  • 3
  • 38
  • 46