为什么变量'name'在第一次使用后不需要被初始化[Javascript] [英] why does variable 'name' doesnt need to be initialized after first use [Javascript]

查看:107
本文介绍了为什么变量'name'在第一次使用后不需要被初始化[Javascript]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



像这样:



p> page1.html

 < html> 
< script>
var name = prompt(你叫什么名字?);
alert(name);
< / script>
< a href ='page2.html'>第2页和LT; / A>
< / html>

page2.html

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

所以在这两个页面中,变量名都保留了它在提示中给出的值第一页,这两页提醒同样的事情,有人可以解释为什么会发生这种情况吗?

你看到的行为是不正常的,并且几乎不会适用于任何其他变量。 name 实际上是Javascript中的一个保留变量,这就是您看到有趣行为的原因。



Javascript是窗口对象的属性。如果您创建了一个名为 age 的变量,您还可以在 window.age 中访问它。 window.name 是当前浏览器窗口的一个特殊属性,它允许给定一个名称,并且该值可以在页面之间保留。



如果您将变量的名称更改为 age ,它将返回按预期工作 - page2.html中的变量将为空。



更多关于 window.name


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?

解决方案

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

这篇关于为什么变量'name'在第一次使用后不需要被初始化[Javascript]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆