我有一个包含一些信息的对象。另一方面,我有一个商店,持有这种对象类型的许多对象。
单个对象应该能够从此商店中删除自己。 我的商店知道一个带有此对象参数的函数“DeleteObjectFromStore”。 现在我想传入对象本身,但我不知道要使用哪种语法。
商店:
class NoteStore {
constructor() {
this.notes = []; // Collection of all notes
}
DeleteNote(note) { // Delete this object from the store
var index = this.notes.indexOf(note);
if (index > -1)
array.splice(index, 1);
}
}
我的对象
class Note {
constructor(noteTitle, noteText, noteStore) {
this.title = noteTitle; // name
this.text = noteText; // content
this.store = noteStore; // dataStore
}
CreateDeleteButton(parentDiv) { // Create a button for deleting itself
var data = this.store;
var deleteBtn = document.createElement("input");
deleteBtn.type = "button";
deleteBtn.value = "Delete";
deleteBtn.onclick = function() {
data.DeleteNote(); // <= missing parameter!
}
parentDiv.appendChild(deleteBtn);
}
}
所以使用关键字这是不正确的。然后我会传递按钮。
有人可以帮助我吗?
答案 0 :(得分:4)
尝试在函数外使用此名称:
CreateDeleteButton(parentDiv) { // Create a button for deleting itself
var data = this.store;
var noteObj = this;
var deleteBtn = document.createElement("input");
deleteBtn.type = "button";
deleteBtn.value = "Delete";
deleteBtn.onclick = function() {
data.DeleteNote( noteObj );
}
parentDiv.appendChild(deleteBtn);
}