简体   繁体   English

如何在函数内访问变量

[英]How to access a variable within a function

How do I access a variable that is defined within a function like this: 我如何访问在函数中定义的变量,如下所示:

var functionVar = function(){
  this.var = 1;
}

console.log(functionVar().var); //MH - obviously this doesn't work, but I'm looking for the command that will log that variable

You can access like this, 您可以像这样访问

var functionVar = function(){
  this.var = 1;
}

 var o = new functionVar();
 alert(o.var)​

a new will do the trick. 一个新的将成功。

var functionVar = function(){
  this.var = 1;
}

console.log(new functionVar().var);

Though not sure what you are trying to achieve by using this code. 尽管不确定使用此代码要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM