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.
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
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;
}
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With