Variable "name" Behavior Discrepancy in JavaScript Objects
In JavaScript, the variable name has been assigned a special role as a string value within the window object (window.name). This unique characteristic can lead to unexpected behavior when using name in conjunction with JavaScript objects.
Consider the following code snippet executed as a global script:
var name = {}; name.FirstName = 'Tom'; alert(name.FirstName);
In Chrome, this code will produce "undefined" when the alert is displayed, while in IE and Firefox, the FirstName property is accessible and displays "Tom."
This discrepancy arises because Chrome explicitly coerces window.name to a string. As a result, the assignment var name = {} essentially sets the global variable name (window.name) to "[object Object]." Since name is now a primitive, attempts to set properties such as name.FirstName will be ineffective.
To resolve this issue, avoid using name as a global variable. By assigning a different variable name, you can ensure that the unique behavior associated with window.name is not inadvertently triggered.
The above is the detailed content of Why Does Assigning `var name = {}` Produce Different Results in Different Browsers?. For more information, please follow other related articles on the PHP Chinese website!