gpt4 book ai didi

javascript - JavaScript 中上下文的困惑

转载 作者:行者123 更新时间:2023-12-03 05:07:03 25 4
gpt4 key购买 nike

我有一个关于 JavaScript 中上下文的问题,我觉得这很令人困惑(可能是因为我总体上是 JavaScript/Web 开发的新手)。我正在调用函数初始化并将其指定为运行它的上下文,在其中我从输入元素订阅 keyup 事件并将其绑定(bind)到此上下文。然而,函数搜索是在窗口函数中调用的,即使它是由在过滤器上下文中调用的函数调用的。为什么会这样呢?我认为函数将在调用者上下文中被调用。

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);
}

用法:

this.filter = new Filter();

最佳答案

我想我找到了答案:

this.searchTimer = setTimeout(search, 250);

替换为

this.searchTimer = setTimeout(search.bind(this), 250);

由于setTimeout的上下文是window,因此search是在window中调用的。

关于javascript - JavaScript 中上下文的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com