JavaScript variable scope question: to var, or not to 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();
}

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)?

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

Thank you!

Daniel


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.

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.

For example:

var content;

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

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


if you dont use var inside the rtest, it is automatically a global variable. which is why it is accessible from other javascript codes including newWindow. now, when you use var, it automatically a variable inside the rtest scope, so the ones that can use it now are those inside the same scope.


It's about the function-scope, if you declare your variable with var , it will be available only in the scope of the function where you did it.

If you don't use the var statement, and you make an assignment to an undeclared identifier (an undeclared assignment), the variable will be added as a property of the Global object.

链接地址: http://www.djcxy.com/p/96524.html

上一篇: 为什么我需要拨打新电话?

下一篇: JavaScript变量范围问题:var,或不var