Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variables with this or var?

Tags:

javascript

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

like image 462
meo Avatar asked Apr 25 '10 20:04

meo


People also ask

Which is correct way to declare variable in?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

Should I use var to declare variable in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browsers, you must use var .

Can you declare a variable without var?

It is Not Recommended to declare a variable without var keyword because it can accidentally overwrite an existing global variable.


1 Answers

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.

like image 177
Christian C. Salvadó Avatar answered Sep 21 '22 15:09

Christian C. Salvadó