简体   繁体   中英

How to assign outer var inside of an arrow function?

I'm trying to assign a value to a variable that is defined outside of an arrow function like this:

    let leftPanel: PerspectivePanel;
    let rightPanel: PerspectivePanel;

    let temp = L.withFlex(1, L.box(direction, [
      L.withFlex(
          1,
          element => {
            element.className = 'gllayoutcell noselect';
            leftPanel = new PerspectivePanel(display, element, perspectiveViewerState);
            this.registerDisposer(leftPanel);
          }),
      L.withFlex(
          1,
          element => {
            element.className = 'gllayoutcell noselect';
            rightPanel = new PerspectivePanel(display, element, perspectiveViewerState2);
            this.registerDisposer(rightPanel);
          }),
    ]))(rootElement);

    leftPanel.otherRenderedDataPanel = rightPanel;
    rightPanel.otherRenderedDataPanel = leftPanel;

But the compiler gives me errors that the variable is being used before being defined. How can I make the variable inside there visible to the outside?

EDIT: What I do not understand how it can be that the arrow function get's called after the two assignments below it. Because clearly it is getting called before them with element being rootElement.

The compiler is complaining because both leftPanel and rightPanel may not have been assigned yet. That's because they are first assigned in one of your arrow functions, for which it is unknown at compile time when they are going to be called.

I'm assuming you use strictNullChecks: true . In that case, you can work around this issue by explicitly stating that each of the two variables can be undefined and then using type assertion:

let leftPanel: PerspectivePanel | undefined;
let rightPanel: PerspectivePanel | undefined;

...

leftPanel!.otherRenderedDataPanel = rightPanel!;
rightPanel!.otherRenderedDataPanel = leftPanel!;

I solved the problem by defining reft and right Panel as class properties and inside of the arrow function I could do this.rightPanel.otherPanel = leftPanel . I still don't know why the other approach did not work, but this was a workaround that for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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