Why Can't I Use 'name' As A Variable/object Name?
Solution 1:
This is happening because name
is a existing property on window
, that behaves a little different from normal variables.
You can't replace this property, you can only assign string values to it. When assigning other types to the name property, it gets cast to string:
name = false;
var name = false;
window.name = false;
These lines will all result in window
having a property name
that contains "false"
.
In a similar fashion, objects and functions saved to the name
variable will be cast to string:
var name = function(){}; // "function (){}"var name = { a: [1, 2] }; // "[object Object]"
If you want to use a variable named "name", you'll have to enclose it in a scope:
// In the global namespace, this will alert `"[object Object]"`var name = { a: 1};
alert('Global `name`: \n' +
JSON.stringify(name));
// In it's own namespace, this will alert `{"a":1}`.
(function(){
var name = { a: 1};
alert('Namespaced `name`: \n' +
JSON.stringify(name));
})()
Solution 2:
Without any enclosing scope, var name
is window.name
, which is a native property which cannot be replaced or overridden. You can assign a string to it, but even then it keeps being an object with special properties:
> name
< "[object Object]"
> name.anchor
< function anchor() {
[native code]
}
> name = null
> name
< "null"
> typeof name
< "string"
> name.anchor
< function anchor() {
[native code]
}
Note that the whole thing works just fine when scoped:
function () {
var name = { .. };
console.log(name.fullName()); 👍
}()
Post a Comment for "Why Can't I Use 'name' As A Variable/object Name?"