why does variable 'name' doesnt need to be

2019-02-28 18:40发布

This question already has an answer here:

Whenever i initialize a variable called 'name' it keeps its value through pages.

Like this:

page1.html

<html>
<script>
    var name = prompt("What's your name?");
    alert(name);
</script>
    <a href='page2.html'> Page2</a>
</html>

page2.html

<html>
   <script>
       alert(name);
   </script>
</html>

So in both pages the variable name keeps the value of what it has been given in the prompt of the first page, the two pages alert the same thing, could someone explain me why this happens?

3条回答
Summer. ? 凉城
2楼-- · 2019-02-28 19:23

The behavior you're seeing isn't normal, and won't work for almost any other variable. name is actually a reserved variable in Javascript, which is why you're seeing interesting behavior.

All variables in Javascript are properties of the window object. If you create a variable called age, you can also access it at window.age. window.name is a special property of the current browser window that allows it to be given a name, and this value can persist between pages.

If you change the name of your variable to age, it will go back to working as expected -- the variable will be empty in page2.html.

A little more about window.name

查看更多
Anthone
3楼-- · 2019-02-28 19:27

The global name variable is the window.name property. It is a string that is indeed persisted across page loads in the same browsing context - if you open the second page in a new tab it should no more "work".

To avoid this, use a safe name for your variable instead, or wrap your code in an IIFE.

查看更多
家丑人穷心不美
4楼-- · 2019-02-28 19:41

It won't keep its value through pages, and the two pages will not alert the same thing.

There must be some other code in your page that sets name to some value.

查看更多
登录 后发表回答