![](/img/trans.png)
[英]Accessing class method inside eventListener function Javascript
[英]Accessing JavaScript class variable inside a class function
我有这个:
function FilterSelect(select, search) {
this.select = select;
this.search = search;
// Get the current list options
this.options = this.select.options;
// Whenever the text of the search box changes, do this
this.search.onkeyup = function() {
// Clear the list
while(this.select.options.length > 0) {
this.select.remove(0);
}
}
}
在onkeyup
函数里面我想访问select
,但我知道它不可能存在。 这样做的正确方法是什么?
在onkeyup函数之前,声明一个变量。 像var _this = this
类的东西然后在keyup函数中,只需使用_this
而不是this
。
所以你的代码看起来像:
var _this = this;
// Whenever the text of the search box changes, do this
this.search.onkeyup = function() {
// Clear the list
while(_this.select.options.length > 0) {
_this.select.remove(0);
}
}
您需要创建一个变量,该变量将保存在onkeyup
函数的闭包范围内:
function FilterSelect(select, search) {
var _this = this; // <-- win
_this.select = select;
_this.search = search;
// Get the current list options
_this.options = this.select.options;
// Whenever the text of the search box changes, do this
_this.search.onkeyup = function() {
// Clear the list
while(this.select.options.length > 0) {
_this.select.remove(0);
}
}
}
通过执行此操作,您可以确保将引用正确的值,而不管调用onkeyup
函数的范围(通常是因为事件而导致的全局/窗口范围)。
编辑
实际上,如果你只需要访问select
,你应该可以这样做:
this.search.onkeyup = function() {
// Clear the list
while(this.select.options.length > 0) {
select.remove(0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.