question

mc avatar image
mc asked

Node.js function call

There following is a custom class method in my index.js:

function getCurrentTaskGuide() {
    if (this.attributes['currentTaskGuide'] == undefined) {
        this.attributes['currentTaskGuide'] = 1;
    }
    else if (!this.attributes['currentTaskGuide']) {
        this.attributes['currentTaskGuide'] = 1;
    }
    return this.attributes['currentTaskGuide'];
}

Within the same file, in my intent blocks, if I want to call the method, the following call works as desired:

var currentTaskGuide = getCurrentTaskGuide.call(this); 

However, the following always returns "undefined":

var currentTaskGuide = getCurrentTaskGuide();

I'm still learning Node.js but can someone explain why I have to use getCurrentTaskGuide.call(this) over getCurrentTaskGuide() ?

alexa skills kitnode_jsnodejsdynamodbattributes
10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

Jenn@amazon avatar image
Jenn@amazon answered

.call(this) passes the 'this' argument to the getCurrentTaskGuide Function. Without it, the function has no context on what base the 'this' upon.

call() method reference

Description:

A different this object can be assigned when calling an existing function. this refers to the current object, the calling object. With call, you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

10 |5000

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.