如何防止具有相同ID的DOM元素覆盖javascript解构分配中的函数参数 [英] how to prevent a function parameter in javascript destructuring assignment from being overrided by DOM element with same ID
问题描述
我正在尝试使用ES6破坏结构分配功能将包含多个参数的options对象传递给函数,但是其中一个参数被具有相同id的DOM元素覆盖!
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 element with the same id!
//javascript function call:
createPicture({name: "aaa", width: 100, height: 100, tags: [] })
//javascript function declaration:
createPicture({name, width, height, tags}) {
console.log(tags) //prints a DOM element with id "tags" instead of an empty array!
}
我知道具有id的DOM元素会在JS中创建全局变量,但是对我来说,在函数调用中它覆盖对象内的属性确实让我感到很奇怪.有什么方法可以保护javascript代码?
I know that DOM elements with ids create global variables in JS, but it is really weird to me that it overrides the attributes within the object in the function call. there is some way to protect the javascript code?
我根据建议添加了JSFiddle以确认该问题.如果在函数声明标记中具有默认值,则会出现该问题.如果将其留空,则没有错误. 在这里拨弄
I added a JSFiddle as suggested to confirm the issue. the problem appears if in the function declaration tags has a default value. if it is let empty, then there is no error. Fiddle here
推荐答案
如果在函数声明标记中具有默认值,则会出现问题
the problem appears if in the function declaration tags has a default value
function createPicture({name, width, height, tags: []}) { … }
这不是默认值,这会进一步破坏-变为空数组模式.它没有声明任何参数,也没有引入任何局部变量,因此当您登录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).
您的模式类似于
function createPicture(arg) {
var name = arg.name,
width = arg.width,
height = arg.height,
[] = arg.tags;
…
}
您实际想要的默认初始化程序写为
The default initialiser you actually wanted is written as
function createPicture({name, width, height, tags = []}) { … }
// ^
这篇关于如何防止具有相同ID的DOM元素覆盖javascript解构分配中的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!