In javascript given this three constructor functions:
function Foo(data) { var _data = data; } function Bar(data) { this.data = data; } function Baz(data) { //just use data freely. }
Is there any difference aside from the visibility of the data
member after construction ? (e.g. you can do new Bar().data
but not new Foo().data
)
Yes, the difference is in how the variable is stored.
The variable declared with var
is local to the constructor function. It will only survive beyond the constructor call if there is any function declared in the scope, as it then is captured in the functions closure.
The variable declared with this.
is actually not a variable, but a property of the object, and it will survive as long as the object does, regardless of whether it's used or not.
Edit:
If you are using variables without declaring them, they will be implicitly declared in the global scope, and not part of the object. Generally you should try to limit the scope for what you declare, so that not everything end up in the global scope.
var _data = data;
creates a local copy (not reference) of data
. this.data = data
actually creates a property of the object itself.
I recommend reading this (no pun intended): http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/
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