繁体   English   中英

如何从与事件侦听器链接的方法访问方法/全局变量?

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

我无法访问 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 变量,现在我已经将 listOfContent 与 click 事件监听器相结合。

错误消息(Index.html:292 Uncaught TypeError: this.addCompon.net is not a function at HTMLDivElement.listOfContent (Index.html:292:22) listOfContent @ Index.html:292)

只需将正常的 function更改为箭头 function ,这样当触发事件click时, this的值为页面 class,而不是HTMLDivElement

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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