简体   繁体   中英

var name and window.name

If I define a JavaScript global variable called name , does that hide the window.name property?

I ask this in the context of the Facebook JavaScript authentication API, since I noticed that having a global of that name would break it, and also since I see that window.name is used in their code.

If name is a global variable, then name and window.name are equivalent.

Global variables and functions are members of the global object. In browsers, the global object contains a window member whose value is the global object.

If you declare a variable in the global scope with var , it will create a property on the global object or write to an existing one (like name ):

var name = 5;
console.log(window.name === '5');  // true
console.log(name === '5');  // true
console.log(Object.getOwnPropertyDescriptor(window, 'name'));
    // object with get and set

var foo = 6;
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
    // object with value

Object.defineProperty(window, 'bar', {
    writable: false,
});

var bar = 7;  // throws in strict mode

var baz;
console.log('baz' in window);  // true

If you declare it with let or const , it won't:

const name = 5;
console.log(window.name);  // likely an empty string
console.log(name === 5);  // true
console.log(Object.getOwnPropertyDescriptor(window, 'name'));
    // same as var

const foo = 6;
console.log(window.foo);  // undefined
console.log(Object.getOwnPropertyDescriptor(window, 'foo'));
    // undefined

Object.defineProperty(window, 'bar', {
    writable: false,
});

const bar = 7;  // succeeds

let baz;
console.log('baz' in window);  // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM