JavaScript 变量作用域问题:到 var,还是不到 var [英] JavaScript variable scope question: to var, or not to var

查看:50
本文介绍了JavaScript 变量作用域问题:到 var,还是不到 var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常感谢.我正在编写一本教科书,他们正在使用一个函数调用另一个打开窗口的函数:

Many thanks in advance. I'm working out of a schoolbook and they're using one function to call another which opens a window:

function rtest(){
   content='dans window';
   oneWindow=open("","Window 1","width=450,height=290");
   newWindow(oneWindow);
}
function newWindow(x){
   x.document.close();
   x.document.open();
   x.document.write(content);
   x.document.close();
   x.moveTo(20,20);
   x.focus();
}

所以一切正常,但我的问题是:newWindow() 函数如何能够访问 rtest() 函数中contents"变量的内容?为什么,如果我在内容"变量前面加上var",就像这样:

So everything works fine, but my question is this: how is the newWindow() function able to access the contents of the "contents" variable in the rtest() function? And why, if I preface the "content" variable with "var", like this:

function rtest(){
  **var content='dans window';**
  oneWindow=open("","OneWindow","width=450,height=290");
  newWindow(oneWindow);
}

...是否抛出错误(并且新窗口的内容留空)?

...does an error get thrown (and the contents of the new window left blank)?

谁能向我解释一下使用 var 和不使用 var 的区别是什么?

Can anybody explain to me what the difference between using var and not using var is?

谢谢!

丹尼尔

推荐答案

如果在原函数内部使用 var 声明变量,它会变成局部变量,在函数外是不可见的.

If you declare the variable using var inside the original function, it will become a local variable and will not be visible outside the function.

如果您根本不声明变量,它将是全局变量.但是,最佳实践是声明全局变量.如果您的教科书没有这样做,请考虑更换它.如果您的教授不这样做,请考虑更换(或改造)他.:-) 如果你说服他有困难,你可以(但不一定应该)提到我是这里的前 200 名用户之一.

If you don't declare the variable at all, it will be global. However, best practice is to declare global variables. If your textbook doesn't do this, consider replacing it. If your professor doesn't do this, consider replacing (or reforming) him. :-) If you have trouble convincing him, you can (but not necessarily should) mention that I'm one of the top 200 users here.

例如:

var content;

function rtest(){
    content='dans window';
    oneWindow=open("","Window 1","width=450,height=290");
    newWindow(oneWindow);
}

另外,打开空白窗口最好的方法是调用open("about:blank", ...),而不是open("", ...).

Also, the best way to open a blank window is to call open("about:blank", ...), not open("", ...).

这篇关于JavaScript 变量作用域问题:到 var,还是不到 var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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