Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these two code fragments the same (using var vs. using this)

Tags:

javascript

I saw some code that looks like this:

function foo(bar) {
   this.bar = bar;
};

can you rewrite it like this:

function foo(bar) {
   var bar = bar;
};

because then you don't need to keep writing this which is nicer. Do these two bits of code do the same thing?

Many thanks.

like image 926
ale Avatar asked Dec 06 '22 08:12

ale


2 Answers

Using this

This creates a property of a object. It is public, with read-write access. Depending on how the function was invoked (with new?), this will point to a different object. More on the subject here.

function foo(bar) {
   this.bar = bar;
};

foo(10);
console.log(bar); // bar or this.bar .. prints 10

var tmp = new foo(20); 
console.log(tmp.bar); // prints 20
console.log(bar);     // still prints 10


Using var

This creates a local variable (note: the variable is already in scope via the function argument). This is local, accesible only from the scope of the foo function.

function foo(bar) {
   var bar = bar;
}


When use which?

Unless you write oo js, you'd probably want to stick with the second option, or even better - skip the redefinition of bar whatsoever. You gain all the usual benefits of encapsulation.

function foo(bar) {
   // just use argument bar 
}
like image 164
emesx Avatar answered Feb 20 '23 18:02

emesx


They are not the same. In the first example you are creating a new property called bar on the foo object, meaning you could do this to access the assigned value from outside the function (used as an object constructor):

function foo(bar) {
   this.bar = bar;
};
var f = new foo(1);
console.log(f.bar);    // => 1

In the second example you're creating a variable called bar which is not accessible outside of the function.

like image 35
Graham Avatar answered Feb 20 '23 17:02

Graham