Are these two code fragments the same (using var vs. using this)
javascript
Solution
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
}
Problem
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.