I am trying to set up an on-click callback for an HTML that causes another node to become visible. Along the way, I was surprised to find out that the following two statemen
In the first example, you're passing the toggle
function for jQuery to execute as the event handler.
However, when jQuery executes the event handler, it sets the value of this
to be the DOM element the event fired on.
toggle
, however, expects it to be the jQuery object (which it would be if called normally), as it uses this.animate() in its implementation.
This is why you see "undefined is not a function", as this.animate
is "undefined", and you're trying to call it as a function.
It's important to appreciate the resolution of this
inside a function is deferred until the function is executed. This means a single function can see a different this
value between invocations. The value of this
can be altered using bind()
, new
, call()
, apply()
or by referencing the object differently; for more info see here, or How does the "this" keyword work?