Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'var' vs 'this' vs constructor-parameter variables [duplicate]

Tags:

javascript

oop

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)

like image 660
Pablo Fernandez Avatar asked Dec 04 '10 16:12

Pablo Fernandez


2 Answers

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.

like image 75
Guffa Avatar answered Sep 21 '22 16:09

Guffa


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/

like image 23
Chris Laplante Avatar answered Sep 18 '22 16:09

Chris Laplante