浏览器中的Javascript Mediator无法查找实例变量

时间:2018-02-22 21:43:30

标签: javascript html class constructor this

正在处理HTML / JS Mediator,当用户在字段中输入文本时,它会过滤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>

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:1)

代码中出现问题:

this.text_field.onchange = this.handle_text_field_changed

默认情况下,如果将方法分配给变量或其他对象的属性,则该方法不会携带其原始绑定上下文。您需要首先以这种方式绑定此handle_text_field_changed方法:

this.text_field.onchange = this.handle_text_field_changed.bind(this)