I’m just trying to understand both JavaScript and Playcanvas engine.
So I made this code and was wondering why the ‘myTimer’ set interval timer doesn’t work. Specifically it says that ‘translateLocal’ is undefined when I’m trying to use my ‘MoveFunction’. I have an idea why this is happening but wanted to be sure. I know there is a solution outside of this by using ‘this.MoveFunction’ in update and initialize. But wanted more clarification to why this is.
myTimer doesn’t exist within the scope of initialize, it only exists after this function has been declared, in ‘window’ scope (I think - I never trust the ‘function funcName()’ pattern - prefer always be explicit: var funcName = function(){}, or window.funcName = function(){} if I want global scope)
Does it work if you use window.myTimer? Or this in combination with var myTimer = function()…? I bet it’d work if you put myTimer func declaration ABOVE the initialise function - I’m not sure what pc does internally with closures, but it’s wholly possible that in your example, myTimer exists trapped in the aether, inaccessible to initialise making an implicitly scoped reference.
In myTimer function, you are calling the function prototype which means it doesn’t have a this reference to the script instance.
The way to do this correctly is to have a reference to the script instance when you set up the callback. You can do this in two ways, through bind or using a closure.
Here is my latest test to better understand this Works exactly as I was expecting. Could you elaborate with me what bind does explicitly? I have a guess that it… well binds it to the object and takes on many of it’s characteristics including translate functions. But I am not sure.