Skip to main content
Known Participant
May 21, 2020
Question

Why use _this vs. this in Javascript interaction?

  • May 21, 2020
  • 1 reply
  • 5829 views

I've seen Javascript used in Animate that defines _this instead of this.

 

For example: _this()stop; or _this.parent.gotoAndPlay

vs.

this()stop; or this.parent.gotoAndPlay

 

The Adobe Press Animate book actually shows screenshots with both used. And, I understand Javascript requires determining scope. Why use one or other and why not just have a standard?

This topic has been closed for replies.

1 reply

Colin Holgate
Inspiring
May 21, 2020

'this' is a reserved word that means the object in which that line of code is. With JavaScript you sometimes need to convery which 'this' you mean. There are generally two ways to do that, either Bind or use a variable.

For example:

 

alert(this);

testfunction();

on testfunction{

alert(this);

}

The two alerts will show different values. Using Bind:

 

alert(this);

testfunction.bind(this);

on testfunction{

alert(this);

}

will show the same value. But, using bind everywhere to keep the level being the same may not always be what you want, and so the other way of using a variable would do:

 

var _this = this;

alert(_this);

on testfunction{

alert(_this);

}

would show the same value. As 'this' is a reserved word it can't be used as a variable, and a common variable to use is _this. I sometimes use 'self' too, like:

var self = this;

Then I can refer to self when I'm trying to do something on the main timeline.

Another approach that is useful is to stash your variables in the browser window level. You could say:

window.tl = this;

and then everywhere in your entire hierarchy you could get back to the main timeline by addressing window.tl.

 

Brainiac
May 21, 2020

Polluting the global scope with variables is not great practice, BTW. At the very least I'd recommend stashing any Animate globals in exportRoot instead, which acts as the defacto Animate namespace.

Inspiring
July 12, 2023

no.

 

you would need to use the correct path to the _this variable (just like every other variable). ie, using

 

var _this = this;

 

is only useful in the frame and timeline wheee it's defined..


ok thanks