30

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)

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232

2 Answers2

28

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    If a variable is never used... does it matter if it exists or not? – Pablo Fernandez Dec 04 '10 at 16:10
  • The variable will survive the constructor call even if it's not used by any method (as long as there exists at least one method). The methods do not have to use the variable - it survives because it is trapped in the scope of the method(s). – Šime Vidas Dec 04 '10 at 16:18
  • @Pablo: Not very much, but it is one effect of the difference between the ways of declaring variables. – Guffa Dec 04 '10 at 16:20
  • @Šime Vidas: Good point. Some languages manage to limit what's included in closures, but if what you say is correct, the closures in Javascript will contain all local variables. – Guffa Dec 04 '10 at 16:25
25

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/

Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • 3
    Note: The local variable is assigned the value of the parameter. If the parameter is a reference to an object, the local variable will also be a reference to the same object, not a reference to a copy of the object. – Guffa May 09 '14 at 09:46