This question already has an answer here:
这个问题在这里已有答案:
- Using the variable “name” doesn't work with a JS object 3 answers
使用变量“name”不能与JS对象3个答案一起使用
Why is it that assigning a DOM element to the global variable "name
" doesn't work ?
为什么将DOM元素分配给全局变量“name”不起作用?
2 个解决方案
#1
2
Most "globals" in JavaScript when running in a browser are actually properties of the window
object (of type Window
).
JavaScript中大多数“全局变量”在浏览器中运行时实际上是窗口对象的属性(Window类型)。
But Window
already has a name
property, so any attempt to assign a non-string to it is going to lead to conversion to a string: the type of the assigned object will not be maintained.
但是Window已经有了一个name属性,因此任何向其分配非字符串的尝试都将导致转换为字符串:不会保留指定对象的类型。
#2
0
While name by itself is a property of the window object, you may still use name with another object as follows:
虽然name本身是window对象的属性,但您仍可以使用name作为另一个对象,如下所示:
var obj2 = { "s1": "spring", "s2": "summer", "s3": "fall", "s4":"winter"};
obj2.name = obj2["s4"];
console.log("Name: " + obj2.name);
obj2.favoriteWeather = obj2.name;
console.log("Favorite season: " + obj2.favoriteWeather);
Resource: MDN Talk: Reserved_Words
资源:MDN Talk:Reserved_Words
#1
2
Most "globals" in JavaScript when running in a browser are actually properties of the window
object (of type Window
).
JavaScript中大多数“全局变量”在浏览器中运行时实际上是窗口对象的属性(Window类型)。
But Window
already has a name
property, so any attempt to assign a non-string to it is going to lead to conversion to a string: the type of the assigned object will not be maintained.
但是Window已经有了一个name属性,因此任何向其分配非字符串的尝试都将导致转换为字符串:不会保留指定对象的类型。
#2
0
While name by itself is a property of the window object, you may still use name with another object as follows:
虽然name本身是window对象的属性,但您仍可以使用name作为另一个对象,如下所示:
var obj2 = { "s1": "spring", "s2": "summer", "s3": "fall", "s4":"winter"};
obj2.name = obj2["s4"];
console.log("Name: " + obj2.name);
obj2.favoriteWeather = obj2.name;
console.log("Favorite season: " + obj2.favoriteWeather);
Resource: MDN Talk: Reserved_Words
资源:MDN Talk:Reserved_Words