javascript 内部函数无法访问外部函数变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12239129/
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-26 15:41:52  来源:igfitidea点击:

Inner function cannot access outer functions variable

javascript

提问by Decrypter

I have created the following jsfiddle which highlights my problem. http://jsfiddle.net/UTG7U/

我创建了以下 jsfiddle,它突出了我的问题。 http://jsfiddle.net/UTG7U/

var ExampleObject = function() {
   var myArray = new Array();
   this.example = function() {
       alert(this.myArray);
   };
}

var exampleObj = new ExampleObject();
exampleObj.example();?

I am new to JavaScript and trying to create an object, field and a method. I can't get my method to access my field variable.

我是 JavaScript 新手,正在尝试创建对象、字段和方法。我无法使用我的方法来访问我的字段变量。

回答by Saket Patel

you were trying to access a local variable using this operator which is wrong, so here is the working example

您试图使用此运算符访问局部变量,这是错误的,所以这是工作示例

var ExampleObject = function() {
   var myArray = new Array(1,2,3);
   this.example = function() {
       alert(myArray);
   };
}
var exampleObj = new ExampleObject();
exampleObj.example();?

Link: http://jsfiddle.net/3QN37/

链接:http: //jsfiddle.net/3QN37/

回答by Raymond Chen

You have confused two types of variables: Local variables and member variables. var myArrayis a local variable. this.myArrayis a member variable.

你混淆了两种类型的变量:局部变量和成员变量。var myArray是局部变量。this.myArray是成员变量。

Solution using only local variables:

仅使用局部变量的解决方案:

var ExampleObject = function() {
   var myArray = new Array(); // create a local variable
   this.example = function() {
       alert(myArray); // access it as a local variable
   };
}

var exampleObj = new ExampleObject();
exampleObj.example();?

Solution using only member variables:

仅使用成员变量的解决方案:

var ExampleObject = function() {
   this.myArray = new Array(); // create a member variable
   this.example = function() {
       alert(this.myArray); // access it as a member variable
   };
}

var exampleObj = new ExampleObject();
exampleObj.example();?

回答by Rhyono

You don't need the this.myArray. Using myArrayalone will suffice (and work).

你不需要this.myArray. myArray单独使用就足够了(并且有效)。

回答by SNAG

alert(myArray);should work fine I think

alert(myArray);我认为应该可以正常工作

回答by Oliver Moran

What thisis changes with the scope of each function. However, myArraywill be visible to inner function. Example:

this每个功能的范围会发生什么变化。但是,myArray对内部函数是可见的。例子:

var ExampleObject = function() {
   var myArray = new Array();
   this.example = function() {
       alert(myArray);
   };
}
var exampleObj = new ExampleObject();
exampleObj.example();?