1

I'm working on Alexa skill and using Node.js for writing my lambda function. I'm also using Alexa SDK for handling Alexa's requests and response. The issue i'm facing is that i'm unable to access "this pointer" in response. Code is as:

var handler = Alexa.CreateStateHandler();
handler['hi'] = function( ) {

console.log("hi intent");

    request(url, function (error, response, body) {

       const message = "Hello there. Best of luck!";
       const reprompt = "Hello there.";

       this.response.speak(message).listen(reprompt);
       this.emit(':responseReady');
    });        
};

Error: this.response not found

FYI: handler['hi'] is a listener and is invoked automatically from Alexa. I can access this pointer outside request block.

I read different answers on SO, but none of them is answering my question. Please help, how can i access "this" inside response.

Fayza Nawaz
  • 2,256
  • 3
  • 26
  • 61
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Joe Clay Nov 01 '16 at 16:26
  • Why are you using `this.response` (a property access) when `response` is a plain variable in your scope? But yeah, it's unclear what `reprompt` and `this.emit` are supposed to be. – Bergi Nov 01 '16 at 17:13
  • @Bergi, this (this.emit, this.response) is alexa-sdk thing. – Fayza Nawaz Nov 01 '16 at 20:06
  • So couldn't you just use `handler.emit` and `handler.response`? Assuming `this === handler` in the `hi` method. – Bergi Nov 01 '16 at 22:10
  • try to replace `console.log("hi intent")` with `console.log(this)`, if the `this` logged is the one with `response` and `emit` you can `.bind` your callback, and then you can do request(url, callBackBinded) – Fi3 Nov 02 '16 at 10:55

1 Answers1

0

Your question is really a javascript question. The js 'this' is different then you might be used to from languages like c/c++, and the problem you are encountering here - accessing 'this' from within a callback - is a common js pitfall so it has already been answered quite well, eg.

How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
Tom
  • 17,103
  • 8
  • 67
  • 75