Why can I pass a function to this object factory, but not use it in the object factory itself?

So to check I have understood what I have learned about javascript objects to date, I decided to make a program based on the 1st edition Advanced Dungeons & Dragons Monster Manual.

I made a object factory which worked, and even allowed me to pass an external function in as a parameter (to damagePerAttack). But then when I tried to use the same function within the factory to calculate hitPoints from hitDice, I always get 0, where I expect to get the sum of this.hitDice rolls of a d8.

Here is the code, why is it not working as desired? Is it because the factory has no values set, so this. does not work at the time you call it?

https://www.codecademy.com/workspaces/647ee38097d700230f487abd

To start with I thought it was because I was using an arrow function for the factory, but then I refactored it to use function instead.

EDIT: Afterwards I can do aerialServant.hitPoints = dice (aerialServant.hitPoints, 8); and then I am able to populate the hitPoints as desired, but is there any way of doing this when the object is created?

1 Like

OK I’ve solved this myself with a web search in the end.

From here:

These [factory] functions do not require the use of the ‘this ’ keyword for inner values. Also, they do not need the ‘newnew’ keyword when initiating new objects.

So if I change:

hitPoints: dice(this.hitDice, 8),

to

hitPoints: dice(hitDice, 8),

everything works as desired! I’ll leave my question and answer up in case it helps someone else. It helped me to describe the problem :sweat_smile:

1 Like

Yeah, the problem here is the confusion of this. In your case, this was referring to the global scope. You can see this if you run console.log(this). This is a very common problem. One way around it is using the bind function.

1 Like

Thank you :+1: I tried console.log(this) and got {}. So what does this mean (no pun intended)? That in the global scope this refers to nothing, so returns an empty object?

1 Like

No worries!

So it depends where you ran your code. If I you ran it in the codecademy workspace I guess that means there is no global scope. When I ran the code in the browser, I got the Window object.

1 Like

Ah OK I was running it in nodejs at my command line.

1 Like

This is another good point. The global scope for node.je is definitely different then in the browser. Mainly because there isn’t a browser!

1 Like