![](/img/trans.png)
[英]How to access javascript variable stored in function closure from browser console?
[英]How to call or access a class method in JavaScript from the browser's console?
我正在學習 JavaScript 並遇到了一個問題,這對於更有經驗的人來說可能不是什么大問題,但這讓我感到困惑。 所以,這是我正在做的事情的一個非常基本的例子。 我得到了兩個文件,guitars.js 和 script.js。
吉他.js:
class Guitars {
constructor(brand, model, type) {
this.brand = brand;
this.model = model;
this.type = type;
}
changeDetails(newBrand, newModel, newType) {
this.brand = newBrand;
this.model = newModel;
this.type = newType;
}
}
export default Guitars
腳本.js:
import Guitars from "./guitars.js";
const newGuitar = new Guitars ("Epiphone", "Les Paul", "electric")
console.log("The new guitar: ", newGuitar)
我在一個 html 文件中有這個,如下所示:
<script type="module" src="guitars.js" defer></script>
<script type="module" src="script.js" defer></script>
當我在瀏覽器中打開控制台時,我可以看到創建了對象及其所有屬性,但是如何訪問/調用該 changeDetails() 方法?
當我將所有內容都放在同一個文件中時,我可以通過鍵入以下內容來訪問所有內容:
newGuitar.changeDetails()
它工作正常。 當我把它分成模塊時,我什么也做不了。
如果有人能幫我解決這個問題,我將不勝感激。
提前致謝。
這里有多種可能的方法。 其中之一可能是將newGuitar
實例存儲在某個全局變量中,然后在您的控制台中訪問它。
因此,嘗試將其添加到 script.js 文件的末尾:
window.newGuitar = newGuitar
然后在您的瀏覽器控制台中,您可以訪問像window.newGuitar.changeDetails()
這樣的方法
注意:在全局變量中存儲實例不是一個好習慣,它應該僅用於某些調試原因等......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.