我无法从一个类调用其他类的方法。我让它工作的唯一方法是传入类(具有方法),然后使用 new 关键字。我不认为在我想使用该方法的每个类中始终使用 new 关键字是正确/好的(当有多个类包含 mult.methods 时)。我怎样才能做到这一点?此外,从其他类继承也不是一个好方法,因为我会继承它的所有属性,而且它不太适合,因为我没有父/子关系。有人能帮忙吗?谢谢!
html:
<input id="title"/>
<input id="description"/>
<button id="add">Add</button>
class EventHandler{
constructor(Todo){}
init() {
const button = document.querySelector("#add");
const todo = new Todo();
button.onclick = todo.addItem;
}
}
class Todo {
constructor(title, description, UIManager){
this.title = title;
this.description = description;
}
addItem() {
const uiManager = new UIManager;
const todoItem = uiManager.getData();
}
}
class TodoManager {
constructor(){}
}
class UIManager {
constructor(){}
getData() {
const title = document.querySelector("#title").value;
const description = document.querySelector("#description").value;
const todoItem = new Todo(title, description);
return todoItem;
}
}
(() => {
const todoManager = new TodoManager();
const uiManager = new UIManager();
const eventHandler = new EventHandler();
let todoItem = uiManager.getData();
eventHandler.init()
})()
ps.: 我正在考虑以某种方式洞察我的 init 函数,但我还没有创建我的 todoitem,无论我在这里尝试什么,我总是收到关于未定义类的错误。
最佳答案
为什么UIManager是一个类?它不会创建任何有用的东西。如果你想要一个函数库,只需使用一个普通对象:
const UIManager = {
getData: () => {
const title = document.querySelector("#title").value;
const description = document.querySelector("#description").value;
const todoItem = new Todo(title, description);
return todoItem;
}
}
与 EventHandler 相同。
如果上述类确实返回了一个您想要使用的有用对象,但您仍想访问与这些对象无关的通用类实用方法,您可以使用static
关键字:
class Something {
constructor() {
this.something = 'somethingelse';
}
static getInfo() {
return 'some info';
}
}
console.log(Something.getInfo());
关于javascript - 如何从javascript es6中的类中的其他类调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479550/