簡體   English   中英

Javascript對象將自身作為參數傳遞

[英]Javascript Object passing itself in as a parameter

我有一個帶有一些信息的物體。 另一方面,我有一家商店,擁有許多這種對象類型的對象。

單個對象應該能夠從該存儲中刪除自己。 我的商店知道帶有該對象參數的函數“ 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);
    }
}

因此,使用關鍵字不正確。 然后,我將通過按鈕。

有人可以幫我嗎?

嘗試在函數外使用一個名稱:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM