简体   繁体   中英

How to access method/global variable from method linked with event listener?

I can't access addComponaner()

 class Page{ page = document.createElement('div'); Compon.net = []; constructor(page, Compon.net){ if (page == null) {} else {this.page = page;} if (Compon.net == null) {} else {this.Compon.net = Compon.net; this.displayAll();} this.page.id = 'page'; this.page.addEventListener("click", this.listOfContent); } addCompon.net(){ this.Compon.net.push(new Text(400,320)); }; listOfContent(){ this.addCompon.net(); this.page.style.borderStylr = solid; this.page.style.display = "inline"; } } class Text{ text = document.createElement('div'); constructor(xpos, ypos){ this.text.style.top = xpos; this.text.style.left = ypos; } }

/page variables now that I've coupled listOfContent with a click eventlistener.

Error message (Index.html:292 Uncaught TypeError: this.addCompon.net is not a function at HTMLDivElement.listOfContent (Index.html:292:22) listOfContent @ Index.html:292)

Just change to so that the value of this is the Page class, not HTMLDivElement when the event click is triggered.更改为 ,这样当触发事件click时, this的值为页面 class,而不是HTMLDivElement

listOfContent = () => {
    this.addComponanet();
    this.page.style.borderStylr = solid;
    this.page.style.display = "inline";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM