Skip to main content
jeffery wright
Inspiring
October 7, 2019
Answered

Cannot read property 'gotoAndStop' of undefined? It is Defined.

  • October 7, 2019
  • 2 replies
  • 2063 views
		function Reset_A() {
		 this.Video_Display.gotoAndStop(0);		
		};
		
		 this.Video_Display.gotoAndStop(0);

 

this.Video_Display.gotoAndStop(0); fires just fine, unless I call it from within in a function...

If I have a function in a click event that fires Reset_A(); then suddenly my Video_Display is "undefined"?

How can it be both defined and undefined?

 

Can anyone make sense of that?

 

Thanks! 

    This topic has been closed for replies.
    Correct answer avid_body16B8

    It is a matter of scope.

    Try to add this code:

    var root = this;

    Then in your function use

    root.Video_Display.gotoAndStop(0);	

     

     

    2 replies

    Legend
    October 7, 2019

    It's not working because you're calling the function as an event handler, and in event handlers, "this" is set to the global window object, not any Animate timeline or object.

     

    You can resolve this problem by binding the event handler function to a specific scope:

     

    somebutton.addEventListener("click", myHandlerFunction.bind(this));

     

    (but that makes removing it a nuisance)

     

    Or you can just stash the current value of "this" in a variable that's within lexical scope of the event handler:

     

    var localThis = this;
    function Reset_A() {
        localThis.Video_Display.gotoAndStop(0);
    };

     

    You can see the value of "this" change by putting alert(this); in your setup code, and again in your event handler function.

    avid_body16B8
    avid_body16B8Correct answer
    Legend
    October 7, 2019

    It is a matter of scope.

    Try to add this code:

    var root = this;

    Then in your function use

    root.Video_Display.gotoAndStop(0);	

     

     

    jeffery wright
    Inspiring
    October 7, 2019

    That did work, but still does not make sense.

    How would anyone have known to do that? I've never had to do that before, why would that be necessary for one function but not for others?
    This seems indistinguishable from invoking magic words, instead of writing code with clear rules. 
    Thank you!

     

    avid_body16B8
    Legend
    October 7, 2019
    Please mark as correct so it helps others when doing a search.