开发者

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

This question already has answers here: Javascript: Do I need to put this.var for every variable in an object? (6 answers) Closed 开发者_JS百科8 years ago.

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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜