实际上没有必要为此使用原型。您不需要创建许多实例,只需在较高级别抽象出一个通用功能,就可以在tasks
对象上添加一个方法。
const tasks = {
start(key) {
const task = this[key]
// do stuff with task
}
}
// example call
tasks.start('123');
如果你想确保有与现有键没有冲突,你可以使用一个Symbol代替。
你也可以只具备一个独立的函数,这样做,同样你addTask
功能:
function start(tasks, key) {
const task = tasks[key]
// do stuff with task
}
// example call
start(tasks, '123')
有了这个独立的功能可能是更好的,因为你不会担心发生冲突您的任务键和方法名称。
您还可以创建一个包装对象,这是否分离:
const taskManager = {
tasks: {} // map of key to task
// methods
add(task) {
this.tasks[task.id] = task;
this.start(task.id);
}
start(key) {
const task = this.tasks[key];
// do stuff with task
}
}
// example usage
taskManager.start('123')
这种方法的好处是,你tasks
封装上他们操纵的容器内,收缩范围在tasks
应使用并使其更清楚(向程序员建议)哪些函数用于任务。
如果您计划在具有多任务管理器,然后用原型可能是有意义的位置:
class TaskManager {
constructor() {
this.tasks = {} // map of key to task
}
// methods
add(task) {
this.tasks[task.id] = task;
this.start(task.id);
}
start(key) {
const task = this.tasks[key];
// do stuff with task
}
}
// example usage
new TaskManager().start('123')
您需要一个构造函数/工厂函数。 – undefined