【问题标题】:Javascript Mediator In Browser Can't Find Instance Variables浏览器中的 Javascript 中介找不到实例变量
【发布时间】: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


    【解决方案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)
    

    【讨论】:

    • 嘿@alcides-queiroz-aguiar,谢谢。确实,执行您的建议使 调用handl_text_field_changed :) 然后我还必须将handle_text_field_changed 更改为handle_text_field_changed(){ this.list_view.innerHTML = this.data_model.filter(this.does_string_start_with_text_field_text.bind(this)) } 问候
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多