first using var
function testCode(some)
{
var something = some;
}
the second using this
function testCode2(some)
{
this.something = some ;
}
In the first function, something
is a private (local) variable, meaning it will be completely inaccessible outside the function; whilst in the second it's a public instance variable. The context on which the variable will be set will depend on how you invoke the function:
> testCode2("foo"); // this will refer to document.window
> something
"foo"
>> var obj = new testCode2("foo"); // this will refer to the new object
>> something
ReferenceError: something is not defined
>> obj.something
"foo"
If those functions are used as functions, the this keyword will make the variable static. If the function is called twice, this.something will still have its value while the first subject will erase the variable data once the function has finished executing.
If you are using them as class constructors, var will define a private variable and this will declare a public variable.
See this fiddle: http://jsfiddle.net/UUFuX/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With