Reputation: 547
I have a question regarding contexts in JavaScript which I find confusing (probably since I'm new to JavaScript/Web dev overall). I am invoking the function initialize and specifying this as the context to run it in, within it I'm subscribing to keyup event from the input element and binds it to this context. However the function search is invoked in window function even though it is invoked by a function that is invoked within the Filter-context. Why is it like that? I thought that a function would be invoked in the invokers context.
function Filter() {
/**
* Other objects are set to this context (Filter)
*/
var search = function() {
/// Context here is window
}
var initialize = function() {
/// Context here is this (Filter)
this.searchBox = $("#search-box");
this.searchBox.keyup((function() {
/// Context here is this (Filter) due to the bind()
var newSearch = this.searchBox.val();
var previousSearch = this.filterValues.search;
if (newSearch !== previousSearch) {
if (newSearch.length === 0)
this.filterValues.Search = null;
else
this.filterValues.Search = newSearch;
clearTimeout(this.searchTimer);
this.searchTimer = setTimeout(search, 250);
}
}).bind(this));
}
initialize.call(this);
}
Usage:
this.filter = new Filter();
Upvotes: 0
Views: 46
Reputation: 547
I think I found the answer:
this.searchTimer = setTimeout(search, 250);
is replaced with
this.searchTimer = setTimeout(search.bind(this), 250);
since setTimeout's context is window, and thus search got invoked in window.
Upvotes: 1