【发布时间】:2018-06-24 14:29:22
【问题描述】:
我可以在子对象 (Todo) 的原型中访问父对象 (TodoList) 的列表对象吗
假设下一个设置:
index.js:
var todoList = new TodoList(form,holder);
todolist.js:
function TodoList(form,holder){
this.list = {};
this.inputField = document.querySelector('input');
this.submitButton = document.querySelector('button');
this.todoHolder = holder;
this.init();
}
TodoList.prototype.init = function(){
this.submitButton.addEventListener('click',this.submitHandler.bind(this));
}
TodoList.prototype.submitHandler = function(e){
var todo = new Todo(this.inputField.value, this.todoHolder);
}
todo.js:
function Todo(value, holder){
this.id = nr++;
this.value = value;
this.checked = false;
this.holder = holder;
this.todoElement = "";
this.template = `
<li id="todo-{{id}}">
<span>{{value}}</span>
<a href="#" class="delete"></a>
<a href="#" class="check"></a>
</li>`;
this.add(this.value);
}
Todo.prototype.add = function(value){
//addToDom
var html = this.template;
this.holder.insertAdjacentHTML('beforeend', html.replace('{{value}}',value).replace('{{id}}',this.id));
this.setUpEventListeners();
////// QUESTION
// HOW CAN I ACCESS THE TODOLIST.LIST object here
// I KNOW I COULD DO todoList.list (but that is by the instance that was created. Is it possible by accessing parent or something like that....
}
【问题讨论】:
-
你使用的是模块加载器,比如 require 吗?由于您的代码位于单独的文件中,因此您可能需要某种类型的模块 common.js 或 AMD
-
您可以将父
TodoList作为Todo构造函数的参数传递。无论如何,您当前的两个参数都是TodoList的成员。 -
那么如何访问索引文件中的 todolist 呢?
-
@Tibrogargan 你能告诉我你的意思吗?
-
@saj 现在我们使用 3 个 js 文件。
标签: javascript object constructor prototype parent-child