我有一個 JavaScript 類,我想讀取并設定selection從另一個檔案呼叫它的屬性,并且我試圖從瀏覽器window物件訪問類/方法,但該類沒有顯示在那里。
我看到其他類,如 JQuery。如何讓我的班級顯示在全域訪問視窗中?
這是我希望做的:
class UI {
constructor() {
this.selection = {}; // I want to read and set this property
}
}
從另一個檔案中,我希望做這樣的事情:
if( window.UI.selection.name ) {
window.UI.selection.name = 'A new name';
};
有沒有辦法讓一個類在全域可訪問window?
uj5u.com熱心網友回復:
如果你想定義一個類并使用它自己的實體變數,你可以這樣做
class UI {
constructor() {
this.selection = {}; // I want to read and set this property
}
}
window.UI = new UI()
window.UI.selection.name = "foo"
console.log(window.UI.selection.name)
如果你想使用沒有new但有靜態變數的類,你可以撰寫以下內容:
class UI {
static selection = {}
}
window.UI = UI
window.UI.selection.name = "foo"
console.log(window.UI.selection.name)
參考:
https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
uj5u.com熱心網友回復:
關于訪問 UI
由于類是現代 JS 的一部分,因此它們let與變數一樣,如果它們是在全域范圍內創建的,它們const不會將自己附加到物件上。window
您可以使用其名稱訪問 UI 類,即使在不同的檔案中,只要您不隱藏UI 變數即可。
<script>
class UI {
constructor() {
this.selection = {}; // I want to read and set this property
}
}
</script>
<script>
console.log(UI);
</script>
例外情況是如果您使用的是模塊,在這種情況下,每個模塊都有自己的范圍。
在這種情況下,您可以顯式分配window物件 ( window.UI = UI),但您不應該這樣做。使用importandexport代替。
訪問 UI.selection.name
selection是由建構式在 UI 類的實體上創建的物件。
它只出現在類的實體上,而不出現在類本身上。
要訪問它,您必須首先創建一個實體:
const ui = new UI();
ui.selection.name = "foo";
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481953.html
標籤:javascript 哎呀
上一篇:不兼容的兩個void函式宣告
下一篇:使用高階函式時無法傳遞引數
