What is the purpose of writing "self = this"?

In many tutorials, I’ve noticed the code var self = this; I thought this was redundant and was skipping this step. However, while debugging a javascript, where I was working with HTML/CSS and DOM objects, I noticed that this was referring to a DOM object, instead of the the entity. Adding the code var self = this; and using self helped me overcome this problem.

Can you explain what is happening in the background - what is this and what is var self = this; meant to avoid?

Thank you! Always grateful for this supportive community.

Hi @Chanelle,

this is a Javascript keyword which refers to the active context (object) that a method is executing in.

For example in Playcanvas scripts, inside a script method like initialize or update, this refers to the script instance. That’s why we can access properties like this.entity or this.app because those are properties of the script instance.

Here is a similar thread that explains a bit more on the subject:

1 Like

Thanks for your help @Leonidas!

Just to tie everything together (my understanding, not a question):
The reason this started to refer to a DOM object was because it was within a callback function. Thus, the active context when that function is called would be the DOM object (which I think is document?) .
e.g.

var button = document.getElementById("button").onClick = function() {
console.log("button clicked");
};

Hi @Chanelle,

This is a good understanding, so this indeed each time refers to the context that the callback function has been called on, unless otherwise specified, using bind() for example.

Not sure what it will return in your code example, that’s something you can easily check:

console.log(this);

So in each case it depends in how every callback is programmed by either the browser APIs or any library you are using.