6

What is the difference between declaring a variable with this or var ?

var foo = 'bar' 

or

this.foo = 'bar' 

When do you use this and when var?

edit: is there a simple question i can ask my self when deciding if i want to use var or this

1
  • For constructors, have a look at this question Commented Jan 22, 2015 at 2:34

7 Answers 7

13

If it is global code (the code is not part of any function), then you are creating a property on the global object with the two snippets, since this in global code points to the global object.

The difference in this case is that when the var statement is used, that property cannot be deleted, for example:

var foo = 'bar'; delete foo; // false typeof foo; // "string" this.bar = 'baz'; delete bar; // true typeof bar; "undefined" 

(Note: The above snippet will behave differently in the Firebug console, since it runs code with eval, and the code executed in the Eval Code execution context permits the deletion of identifiers created with var, try it here)

If the code is part of a function you should know that the this keyword has nothing to do with the function scope, is a reserved word that is set implicitly, depending how a function is called, for example:

1 - When a function is called as a method (the function is invoked as member of an object):

obj.method(); // 'this' inside method will refer to obj 

2 - A normal function call:

myFunction(); // 'this' inside the function will refer to the Global object // or (function () {})(); 

3 - When the new operator is used:

var obj = new Constructor(); // 'this' will refer to a newly created object. 

And you can even set the this value explicitly, using the call and apply methods, for example:

function test () { alert(this); } test.call("hello!"); //alerts hello! 

You should know also that JavaScript has function scope only, and variables declared with the var statement will be reachable only within the same function or any inner functions defined below.

Edit: Looking the code you posted to the @David's answer, let me comment:

var test1 = 'test'; // two globals, with the difference I talk this.test2 = 'test'; // about in the beginning of this answer //... function test4(){ var test5 = 'test in function with var'; // <-- test5 is locally scoped!!! this.test6 = 'test in function with this'; // global property, see below } test4(); // <--- test4 will be called with `this` pointing to the global object // see #2 above, a call to an identifier that is not an property of an // object causes it alert(typeof test5); // "undefined" since it's a local variable of `test4` alert(test6); // "test in function with this" 

You can't access the test5 variable outside the function because is locally scoped, and it exists only withing the scope of that function.

Edit: In response to your comment

For declaring variables I encourage you to always use var, it's what is made for.

The concept of the this value, will get useful when you start working with constructor functions, objects and methods.

Sign up to request clarification or add additional context in comments.

3 Comments

You're welcome @meo, if anything is not clear don't hesitate to comment.
is there a simple question i can ask my self when deciding if i want to use var or this?
@meo, for declaring variables use always var, is what is made for.
5

If you use var, the variable is scoped to the current function.

If you use this, then you are assigning a value to a property on whatever this is (which is either the object the method is being called on or (if the new keyword has been used) the object being created.

3 Comments

so how it comes that i can't access to var test5 but i can to test6 in the following example: jsfiddle.net/Ew3pD ?
@meo Because test 5 loses it's scope once test 4 function is left. When you're calling this.test6, you're creating a variable on the global scope because the function isn't being called on an object.
@meo: test6 is being assigned to this when a function is called without context object the global object is assumed. Properties create on the global object are synonymous (but identical to) variables created at the global level. You cannot create a property on the global object with the same name as a variable at the global level because they are both held against the global object.
3

You use var when you want to define a simple local variable as you would in a typical function:-

function doAdd(a, b) { var c = a + b; return c; } var result = doAdd(a, b); alert(result); 

However this has special meaning when call is used on a function.

function doAdd(a, b) { this.c = a + b; } var o = new Object(); doAdd.call(o, a, b); alert(o.c); 

You note the first parameter when using call on doAdd is the object created before. Inside that execution of doAdd this will refer to that object. Hence it creates a c property on the object.

Typically though a function is assigned to a property of an object like this:-

function doAdd(a, b) { this.c = a + b; } var o = new Object(); o.doAdd = doAdd; 

Now the function can be execute using the . notation:-

o.doAdd(a, b); alert(o.c); 

Effectively o.doAdd(a, b) is o.doAdd.call(o, a, b)

Comments

3
var foo = 'bar' 

This will scope the foo variable to the function wrapping it, or the global scope.

this.foo = 'bar' 

This will scope the foo variable to the this object, it exactly like doing this:

window.foo = 'bar'; 

or

someObj.foo = 'bar'; 

The second part of your question seems to be what is the this object, and that is something that is determined by what context the function is running in. You can change what this is by using the apply method that all functions have. You can also make the default of the this variable an object other than the global object, by:

someObj.foo = function(){ // 'this' is 'someObj' }; 

or

function someObj(x){ this.x=x; } someObj.prototype.getX = function(){ return this.x; } var myX = (new someObj(1)).getX(); // myX == 1 

Comments

1

In a constructor, you can use var to simulate private members and this to simulate public members:

function Obj() { this.pub = 'public'; var priv = 'private'; } var o = new Obj(); o.pub; // 'public' o.priv; // error 

1 Comment

Actually o.priv; doesn't makes an error, it will just return undefined :)
1

Example for this and var explained below:

 function Car() { this.speed = 0; var speedUp = function() { var speed = 10; // default this.speed = this.speed + speed; // see how this and var are used }; speedUp(); } 

1 Comment

Note that the this value of the speedUp function will be always the global object, since it's invoked with no object context (speedUp();), it has nothing to do with the outer this.speed, unless the Car function is called without the new operator. In that case this in the outer function will refer also to the global object, leaking a speed global variable (window.speed).
1
var foo = 'bar'; // 'var can be only used inside a function 

and

this.foo = 'bar' // 'this' can be used globally inside an object 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.