最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - var name and window.name - Stack Overflow

programmeradmin5浏览0评论

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 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.

Share Improve this question edited Jun 16, 2012 at 15:51 Ry- 225k56 gold badges492 silver badges499 bronze badges asked Jun 16, 2012 at 15:47 Steve TealeSteve Teale 2193 silver badges9 bronze badges 1
  • 1 Related: stackoverflow./questions/10523701/… – melpomene Commented Jun 7, 2019 at 9:43
Add a ment  | 

2 Answers 2

Reset to default 6

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
发布评论

评论列表(0)

  1. 暂无评论