【发布时间】:2018-02-22 21:43:29
【问题描述】:
我正在开发一个 HTML/JS 中介器,当用户在字段中输入文本时过滤 data_model。使用了window.onload = init,并花了四个小时试图找出为什么浏览器中的“this”会打印调用对象,因此我无法使用“this”来引用自己的类实例
console.log(this.text_field)
在 setup_list_view() 中工作正常,似乎是因为它在构造函数范围内。在构造函数之外运行它,如下所示:
Cannot set property 'innerHTML' of undefined at HTMLInputElement.handle_text_field_changed
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
function init() {
var text_field = document.getElementById("text-field");
var list_view = document.getElementById("list-view")
form_mediator = new FormMediator(text_field, list_view)
}
class FormMediator {
constructor(text_field, list_view) {
this.setup_text_field(text_field)
this.setup_list_view(list_view)
}
setup_text_field(text_field) {
this.text_field = text_field;
this.text_field.onchange = this.handle_text_field_changed
}
setup_list_view(list_view) {
this.data_model = ['England', 'Estonia', 'France', 'Germany']
this.list_view = list_view
this.list_view.innerHTML = this.data_model
}
does_string_start_with_text_field_text(text) {
return false;
return text.startsWith('E')
}
handle_text_field_changed(){
this.list_view.innerHTML = 'new content' //this.data_model.filter(this.does_string_start_with_text_field_text)
}
}
window.onload = init
</script>
<input id="text-field"><button>Search</button>
<span id="list-view"></span>
</body>
</html>
非常感谢任何帮助。
【问题讨论】:
标签: javascript html class constructor this