Skip to content Skip to sidebar Skip to footer

How To Prevent A Function Parameter In Javascript Destructuring Assignment From Being Overrided By Dom Element With Same Id

I am trying the ES6 destructuring assignment feature to pass an options object containing multiple parameters to a function, but one of the parameters is being overridden by a DOM

Solution 1:

the problem appears if in the function declaration tags has a default value

function createPicture({name, width, height, tags: []}) { … }

That's not a default value, that's further destructuring - into an empty array pattern. It doesn't declare any parameter, it doesn't introduce any local variables, so when you log tags you do indeed get the global one (which refers to the DOM element for legacy reasons).

Your pattern works like

functioncreatePicture(arg) {
    var name = arg.name,
        width = arg.width,
        height = arg.height,
        [] = arg.tags;
    …
}

The default initialiser you actually wanted is written as

functioncreatePicture({name, width, height, tags = []}) { … }
//                                                ^

Post a Comment for "How To Prevent A Function Parameter In Javascript Destructuring Assignment From Being Overrided By Dom Element With Same Id"