访问函数内部的影子根



我使用香草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"。(不幸的是,在不了解你的代码的情况下,我不知道这个建议有多有用。)

最新更新