首页 > 解决方案 > 在函数内访问影子根

问题描述

我已经使用 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 )的意思。

标签: javascripthtmlthisweb-component

解决方案


我能提供的最简单的解决方案是停止使用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”。(不幸的是,在不知道您的代码的情况下,我不知道这个建议有多大用处。)


推荐阅读