javascript 'var' vs 'this' vs 构造函数参数变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4354418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:09:07  来源:igfitidea点击:

'var' vs 'this' vs constructor-parameter variables

javascriptoop

提问by Pablo Fernandez

In javascript given this three constructor functions:

在javascript中给出了这三个构造函数:

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 datamember after construction ? (e.g. you can do new Bar().databut not new Foo().data)

除了data构件在施工后的可见度之外,还有什么不同吗?(例如,你可以做 newBar().data但不能new Foo().data

采纳答案by Chris Laplante

var _data = data;creates a local copy (not reference) of data. this.data = dataactually creates a property of the object itself.

var _data = data;创建 . 的本地副本(不是引用)datathis.data = data实际上创建了对象本身的属性。

I recommend reading this (no pun intended): http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

我建议阅读这个(没有双关语):http: //javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/

回答by Guffa

Yes, the difference is in how the variable is stored.

是的,不同之处在于变量的存储方式。

The variable declared with varis 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.

声明的变量var是构造函数的局部变量。如果在作用域中声明了任何函数,它只会在构造函数调用之后继续存在,因为它随后在函数闭包中被捕获。

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.

用 with 声明的变量this.实际上不是变量,而是对象的一个​​属性,只要对象存在,它就会一直存在,不管它是否被使用。

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.

编辑:
如果您使用变量而不声明它们,它们将在全局范围内隐式声明,而不是对象的一部分。通常,您应该尝试限制您声明的范围,以便并非所有内容都在全局范围内结束。