JavaScript loses context on variable when passed through functions

  Kiến thức lập trình

Im using Miro SDK for plugin development with JS and React.

I read that JS is semi-link type language where when you pass a variable (and work with it) you working with link to this variable and can modify their values which will be ‘updated’ from bottom to surface in functions calls.

But with this particular situation i seem to lose my modifications to value in my varibale.

In here i create a variable highlight because later i call ‘await highlightOn’ or ‘await highlightOff’:

async function createHighlight(item, borderColor, isItemOn) {
    console.log("isItemOnInside createHighlight: ", isItemOn);
    let borderOpacity = 1; //this is my workaround
    let borderWidth = isItemOn ? 9 : 3; //this is my workaround
    let highlight = await miro.board.createShape({
        type: 'shape',
        shape: item.shape,
        style: {
            fillColor: 'transparent',
            borderColor: borderColor,
            borderOpacity: borderOpacity,
            borderWidth: borderWidth
        },
        x: item.x,
        y: item.y,
        height: item.height + 16,
        width: item.width + 12
    });
    await highlight.sendBehindOf(item);
    await highlight.setMetadata(IS_HIGHLIGHT_ON, isItemOn);
    if (isItemOn) { //this is where i get trouble
        await highlightOn(highlight);
    } else await highlightOff(highlight);
    await addToGroup(highlight, item);
    await highlight.sync();
    return highlight;
}

In those functions (which are in same JS file) i change style value of my variable (highlightOff is same):

export async function highlightOn(item) {
    console.log("highlightOn triggered");
    item.style.borderOpacity = 1;
    item.style.borderWidth = 9;
    console.log(item);
    await item.setMetadata(IS_HIGHLIGHT_ON, true);
}

And without workaround i just doesn’t get these changes to values of my variable. But i see in my log that i triggered my functions

isItemOnInside createHighlight:  true
highlightService.js?t=1718108650801:106 highlightOn triggered

I tried to return my variable inside functions like return item after updates but that doesn’t help.

So why can’t i update my variable’s values when i pass it to another function in same JS scrip (or from another script for that matter)?

LEAVE A COMMENT