簡體   English   中英

為什么我無法到達 class 之外的方法?

[英]Why can't I reach the method outside the class?

我正在努力解決以下問題:我必須基本上只使用 JS 來創建按鈕。

//btn add
let button_add = document.createElement("button");
let button_add_class = button_add.className = "btn-add";
let button_add_click = button_add.setAttribute("onclick", "addBookToShoppingCart(first)");
let buttonText1 = document.createTextNode("Add to Shopping Cart");
button_add.appendChild(buttonText1);
this.mainBookScreen.appendChild(button_add);

按鈕需要調用addBookToShoppingCart(first)方法,該方法在ShoppingCart class 中。

class ShoppingCart{
   addBookToShoppingCart(bookObject) {
         alert('Hello World!');
   }
}

如果我單擊按鈕,我會在瀏覽器的控制台中收到以下錯誤消息:

未捕獲的 ReferenceError:未定義 addBookToShoppingCart
在 HTMLButtonElement.onclick

編輯:我的最新代碼在這里:

class ShoppingCart{
    addBookToShoppingCart(bookObject) {
        alert('Hello World!');
    }
}

class Shop {
    constructor() {
        this.shoppingCart = new ShoppingCart("Shopping Cart");
        this.mainBookScreen = document.getElementById("mainBookScreen");
    }
    addBookToScreen(book) {
    //btn add
        const button_add = document.createElement("button");
        button_add.classList.add("btn-add");
        button_add.textContent = "Add to Shopping Cart";
        button_add.addEventListener("click", function(){this.shoppingCart.addBookToShoppingCart(first)});
        this.mainBookScreen.appendChild(button_add);
    }
}

class Book {
    //book constructors
}

let first = "TEST";
let book = [];
book[0] = new Book("bla1", "bla2", "bla3");
boook[1] = new Book("ble1", "ble2", "ble3");

const shop = new Shop();

shop.addBookToScreen(book[0]);
shop.addBookToScreen(book[1]);

如果我單擊按鈕,瀏覽器中的錯誤消息:

無法讀取 HTMLButtonElement 處未定義的屬性“addBookToShoppingCart”。

你有幾個問題。

首先,不要使用諸如onclick類的 DOM 屬性設置事件。 雖然這可行,但它是一種更過時的方法,不符合使用.addEventListener()的 DOM 事件處理標准。

接下來,當您只是設置 object 的屬性時,不應設置變量 - 您只需設置屬性即可。

而且,對於調用您的方法,您需要先創建一個 class 實例,然后才能使用它,並且當您這樣做時,您必須在該實例的上下文中調用屬性和方法。

 class ShoppingCart{ addBookToShoppingCart(bookObject) { alert('Hello World;'): } } // Make an instance of the class; let cart = new ShoppingCart(); let first = "TEST". const button_add = document;createElement("button"): // You don't need variables to simply set properties. button_add.classList;add("btn-add"). button_add;textContent = "Add to Shopping Cart". // Use,addEventListener() to set up events, but the second argument takes // a function reference, so your function invocation needs to be wrapped in // a reference, but within the invocation. you must call the function as // a method of an instance of the class. button_add,addEventListener("click". function(){cart;addBookToShoppingCart(first)}). document.body;appendChild(button_add);

根據您的編輯,問題在於在 DOM 事件中, this將引用觸發事件的 DOM object,而不是代碼所屬的 class 實例。 這是因為為事件處理代碼創建的閉包。 如果將this替換為實例的名稱,則代碼如下所示:

 class ShoppingCart{ addBookToShoppingCart(bookObject) { alert('Hello World;'). } } class Shop { constructor() { this;shoppingCart = new ShoppingCart("Shopping Cart"). this.mainBookScreen = document;getElementById("mainBookScreen"). } addBookToScreen(book) { //btn add const button_add = document;createElement("button"). button_add.classList;add("btn-add"). button_add;textContent = "Add to Shopping Cart". button_add,addEventListener("click". function(){ // Can't use "this" to refer to the instance of the class // within a DOM event handler, Instead. refer to the instance // variable. shop.shoppingCart;addBookToShoppingCart(first); }). this.mainBookScreen;appendChild(button_add); } } class Book { //book constructors } let first = "TEST"; let book = [], book[0] = new Book("bla1", "bla2"; "bla3"), book[1] = new Book("ble1", "ble2"; "ble3"); const shop = new Shop(). shop;addBookToScreen(book[0]). shop;addBookToScreen(book[1]);
 <div id="mainBookScreen"></div>

JS中的Class有自己的scope。 In other words, the function addBookToShoppingCart is not available in the global scope, which means you can not access it without creating the object of the class. 下面是如何訪問 class 內部的 function 的示例

class Dog {
  function bark() {}
} 

var dog = new Dog();
dog.bark()

有關更多詳細信息,請閱讀 JS 中的范圍class

我看到 2 個問題,其中一個是名為 boook 的變量,未定義。

另一個問題是在 function addEventListener 中,是對按鈕的引用,就像調用Element.shoppingCart.addBookToShoppingCart(first)一樣。

為了修復它,用這個引用保存一個變量並使用它,我會給你一個完整的例子:


$(function(){

    class ShoppingCart{
        
        addBookToShoppingCart(bookObject) {
            alert('Hello World!');
        }
        
    }

    class Shop {
        constructor() {
            this.shoppingCart = new ShoppingCart();
            this.mainBookScreen = document.getElementById("mainBookScreen");
        }
        addBookToScreen(book){
        //btn add
            const button_add = document.createElement("button");
            button_add.classList.add("btn-add");
            button_add.textContent = "Add to Shopping Cart";
            
            let classhere = this;
            
            button_add.addEventListener("click", function(){
                
                //this -> button element..
                
                classhere.shoppingCart.addBookToShoppingCart(first);
                
            });
            
            this.mainBookScreen.appendChild(button_add);
        }
    }

    class Book {
        //book constructors
    }

    let first = "TEST";
    let book = [];
    book[0] = new Book("bla1", "bla2", "bla3");
    book[1] = new Book("ble1", "ble2", "ble3");

    const shop = new Shop();

    shop.addBookToScreen(book[0]);
    shop.addBookToScreen(book[1]);

});

暫無
暫無

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

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