18910140161

JavaScript-访问函数中的影子根-堆栈溢出

顺晟科技

2022-10-18 14:11:16

227

我已经使用普通的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)来访问,这意味着。


顺晟科技:

我能提供的

最简单的解决方案是停止使用thisthis的含义随着每个函数的调用而变化,这就是为什么您在理解代码中的任何一点时都很难理解它所指的内容。

例如,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 ”。(不幸的是,在不了解代码的情况下,我不知道这个建议有多大用处。)

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航