JavaScript 类 中的调用方法

Calling Methods in JavaScript Classes

我在 JavaScript 中得到了一个 class。在这个 class 中,我有一个检查文本字段输入的方法。当 html 文档正文加载时,我想第一次调用这个方法。之后,我想使用 "onchange()" 事件。

//##############
//# Javascript #
//##############

class NoteController{
  constructor() {
    this.store = new NoteStore(); // instance of a dataStore
  }

  HandleInputFields(){ // Enable / Disable a button by validation
    var input = document.getElementById('edtNoteTitle').value; // Get the input text from the field
    var inputIsValid = true;

    if(input.length < 1) // text is empty
        inputIsValid = false;
    else if (this.store.notes.some(n => n.title === input)) // check for duplicates in the store
        inputIsValid = false;

    document.getElementById('btnCreateNote').disabled = !inputIsValid; // disable the button or keep it enabled
  }
}

//########
//# HTML #
//########

<body onload="HandleInputFields()"> // Disable the button when loading the Document

<input type="text" id="edtNoteTitle" onchange="HandleInputFields()"> // Validate the Input field

</body>

所以当我打开文档时,它说,"HandleInputFields()" 未定义。如何正确调用此方法?

您需要将该方法定义为 static 方法并通过其 class 范围访问它。

所以在class NoteController { ...

HandleInputFields() { 更改为 static HandleInputFields() { 然后通过

访问它
<body onload="NoteController.HandleInputFields()">

说明:目前您正在尝试访问不带回退到 window.HandleInputFields() 的上下文的方法。然而,您的意图是通过 NoteController 的上下文访问它,因此调用 NoteController.HandleInputFields()。但是,为了能够直接在 class 而不是实例上进行调用,您需要将其定义为 static.