如何从父对象构造函数访问对象

时间:2018-01-15 22:50:42

标签: javascript object constructor prototype parent-child

我可以在子对象原型(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....      
}

1 个答案:

答案 0 :(得分:2)

创建TODO的父对象应该添加引用,如下所示:

TodoList.prototype.submitHandler = function(e){
  var todo = new Todo(this.inputField.value, this.todoHolder);
  todo.parent = this
}

现在这不适用于您当前的设置,因为add方法正在todo.parent设置之前的构造函数中调用。

所以为了解决这个问题,你应该把它传递给Todo的init

TodoList.prototype.submitHandler = function(e){
  var todo = new Todo(this, this.inputField.value, this.todoHolder);
}

这意味着:

function Todo(parent, value, holder){
  this.parent = parent 
  // rest of logic...
}

Todo.prototype.add = function(value){
  console.log(this.parent)
}