實際上沒有必要爲此使用原型。您不需要創建許多實例,只需在較高級別抽象出一個通用功能,就可以在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