[英]Inner function cannot access outer functions variable
I have created the following jsfiddle which highlights my problem. 我创建了以下jsfiddle,突出了我的问题。 http://jsfiddle.net/UTG7U/
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. 我是JavaScript的新手,并尝试创建一个对象,字段和方法。 I can't get my method to access my field variable.
我无法获取我的方法来访问我的字段变量。
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/
You have confused two types of variables: Local variables and member variables. 您混淆了两种类型的变量:局部变量和成员变量。
var myArray
is a local variable. var myArray
是一个局部变量。 this.myArray
is a member variable. 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();
You don't need the this.myArray
. 你不需要
this.myArray
。 Using myArray
alone will suffice (and work). 单独使用
myArray
就足够了(并且可以工作)。
alert(myArray);
should work fine I think 我认为应该工作正常
What this
is changes with the scope of each function. this
是每个功能范围的变化。 However, myArray
will be visible to inner function. 但是,
myArray
对内部函数可见。 Example: 例:
var ExampleObject = function() {
var myArray = new Array();
this.example = function() {
alert(myArray);
};
}
var exampleObj = new ExampleObject();
exampleObj.example();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.