Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between a 'var' declared variable and 'this' created property in Javascript?

Tags:

javascript

first using var

 function testCode(some) 
    {
         var something = some;
    }

the second using this

function testCode2(some) 
{
     this.something = some ;
}
like image 879
Adam Lee Avatar asked Aug 23 '12 15:08

Adam Lee


2 Answers

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"

Reference:

  • Private Members in JavaScript, by Douglas Crockford
like image 75
João Silva Avatar answered Oct 19 '22 23:10

João Silva


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/

like image 25
Salketer Avatar answered Oct 20 '22 00:10

Salketer