我想在 Base 類上為組件設定 html 命名空間,但似乎你不能不NavBar.ns創建實體,這會使 Web 組件無法呈現。
import Base from './Base.js';
class NavBar extends Base {
constructor() {
super();
}
connectedCallback() {
console.log('ns', this.ns);
this.innerHTML = '...';
}
}
console.log('ns2', NavBar.ns); // undefined here
customElements.define(`${NavBar.ns}-navbar`, NavBar);
Base.js:
class Base extends HTMLElement {
constructor() {
super();
this.ns = 'wce';
}
}
export default Base;
uj5u.com熱心網友回復:
您無法訪問Navbar.ns,因為您沒有創建 Navbar 的實體(物件),并且this.ns將應用于每次new呼叫 navbar,例如const navbar = new Navbar(); navbar.ns; // <-- wce. 您沒有創建 的實體,Navbar因此您可以創建一個靜態欄位,它允許您在不創建類實體的情況下訪問欄位。
在base.js:
class Base extends HTMLElement {
constructor() {
super();
}
static get ns() {
return 'wce';
}
}
export default Base;
static允許我們在不創建實體的情況下且僅在不創建new實體的情況下訪問類欄位。
現在,當您呼叫NavBar.ns它時,它將"wce"使用getter回傳。
但是,您還希望能夠.ns在 ( customElements.define) 創建新實體時進行訪問。您必須設定一個附加this呼叫:
class Base extends HTMLElement {
constructor() {
super();
this.ns = 'hello';
}
static get ns() {
return 'world';
}
}
export default Base;
在您的情況下,如果您希望它們“以相同的方式作業”,您可以將“hello”和“world”都更改為“wce”。
現在,假設您要訪問ns,如果您不創建實體,您會這樣做:
NavBar.ns; // <-- "world"
但是如果你正在創建一個實體(比如 in customElements.define),你可以使用new運算子來訪問this.ns:
const navbar = new NavBar();
navbar.ns; // "hello"
(I used "hello" and "world" instead of "wce" just for the illustration.)
Now with the added code you could use it as in your example:
/* "wce-navbar" */
customElements.define(`${NavBar.ns}-navbar`, NavBar);
Some docs about static.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/425426.html
標籤:javascript ecmascript-6 网络组件 本机网络组件
