I will not completely re-iterate how the this
keyword works, but there's an exhaustive explanation here.
In JS when the default this
behaviour is not altered
Keeping things simple, to know the object to which the this
keyword refers to you can simply look at the left-side of the .
in a function invocation.
For example, in myObj.someFunction()
, the this
keyword within someFunction
will point to myObj
(that is unless the function has been bound using Function.prototype.bind
).
If the function is not invoked on an object, such as someFunction()
, then this
will point to the global object which is window
in browsers.
This is also the case within anonymous functions that are passed around, except for addEventListener
, which will make sure that the this
value within the handler is the object to which the handler was attached.
E.g.
setTimeout(function () { this; /*window*/ }, 10);
document.addEventListener('click', function (e) {
e.target; //the clicked DOM element
this; //the document
});
When this
is altered by the API
Using Function.prototype.call
or Function.prototype.apply
, it is possible to specify the object to which this
will point to during a function execution.
Some libraries (e.g. jQuery) are taking advantage of that feature to make this
point to an object that is more intuitive, rather than the global object.
E.g.
$('#someEl').on('click', function (e) {
this; //the DOM element that was clicked (not the jQuery wrapper)
});
When this
is altered in such way by the library, there is no other way than looking at the library's documentation to see what this
will be.
We can read from jQuery event docs that:
In addition to the event object, the event handling function also has
access to the DOM element that the handler was bound to via the
keyword this.
Rewriting your function
Now, here's how you could re-write your function:
$(".trigger").click(function () {
var $this = $(this).toggleClass('toggle'),
$elementToSlide = $this.closest("td").next().find(".clueless > div"),
isToggled = !$this.hasClass('toggle'),
slideBehavior = isToggled? 'slideUp' : 'slideDown';
$elementToSlide[slideBehavior]();
});