javascript - 在函数内访问影子根
问题描述
我已经使用 vanilla javascript 创建了简单的 Web 组件
问题出在我hideNonVisibleDivs()
想访问shadowRoot
这是我的功能。
var visibleDivId = null;
var i, divId, div;
console.log('shadowroot', this); // display the global shadow root element
function divVisibility(divId) {
hideNonVisibleDivs.bind(this)(divId); //binding this context
}
function hideNonVisibleDivs(divId) {
//I want to access a shadow root here using this
console.log('shadowroot', this); //undefined
}
var panels = this.shadowRoot.querySelectorAll("#tab-info> .share-tab")
panels.forEach(function(el) {
divVisibility.bind(this)(this.getAttribute('custom-id')); //bind this context
});
});
什么是预期的?
在里面hideNonVisibleDivs(divId)
我想访问 shadowRoot 作为外部函数(全局 shadowroot )的意思。
解决方案
我能提供的最简单的解决方案是停止使用this
.
每个函数调用的含义this
都会发生变化,这就是为什么您在代码中的任何时候都无法理解它所指的内容。
例如,您的divVisibility()
函数无法工作。
console.log( 'shadowroot', this ); //{this} is a shadowroot
//...
function divVisibility(divId) {
//shadow root {this} cannot be accessed at all from here
hideNonVisibleDivs.bind(this)(divId); //binding this context
//^Refers to divVisibility
}
尝试在不使用this
任何地方的情况下重写您的代码。相反,请使用变量名称,例如“shadowroot”。(不幸的是,在不知道您的代码的情况下,我不知道这个建议有多大用处。)
推荐阅读
- javascript - 连接页面和 React-bootstrap Nav
- yaml - YAML 配置将一个属性值替换为另一个属性值
- flutter - StreamProvider 更新时如何让 Navigator 保持在活动路径上?
- java - 如何在Java中使用字符串获取对象
- android - 必须单击对话框两次才能关闭,从首选项片段中的 listpreference 启动对话框
- python-3.x - apscheduler+scrapy+asyncio 无法顺利执行第一个任务
- reactjs - 如何在传递给复选框的字符串中添加锚标记
- javascript - Google Chrome 扩展程序:如何在地址栏中添加图标?
- node.js - 处理nodejs数据库异步函数的最佳方法是什么
- java - SharedPreferences 并检查用户是否已登录