Robert Mark Bram said:
Must I *always* precede an instance variable with "this" in JavaScript?
If by an "instance variable" you mean a property of an object, then
you must always[1] access it as part of an object. That object might
be referenced by the "this" keyword.
For example, consider the code below:
var initialDate;
function DateControl (initialDate)
{
this.initialDate = initialDate;
}
function doSomething()
{
alert ("typeof initialDate: " + (typeof initialDate));
}
Should initialDate be undefined and this.initialDate be a date?
When this code executes, nothing happens except the creation of two
functions and one global variable.
If you call "doSomething" after this, the scope rules tells us that
"initialDate" inside "doSomething" refers to the global variable.
It is still uninitialized, so the alert reports a type of "undefined".
If you create a new object with "new DateControl(foo)", then during
the execution of the "DateControl" function, the scope rules tells us
that "initialDate" refers to the argument of the "DateControl"
function. When using a function as a constructor, the "this" keyword
refers to the object being created. It then goes on to create a
property on the newly created object. That property is also called
"initialDate", and its value is set to the value of the argument.
If you call "DateControl" as a function (not as a constructor with the
"new" keyword), then inside the body of the function, "this" refers to
the global object. It then sets the property called "initialDate" of the
global object to the value of its argument. The global object contains
the global variables, so this changes the value of the global variable
called "initialDate".
Or should they both be date?
---
var x = 4;
function cx(x) {
this.x=x;
}
var z = new cx("foo");
var y = new cx(true);
cx( function(){var x=42;} );
alert(typeof x + "," + typeof z.x + "," + typeof y.x);