最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Inner function cannot access outer functions variable - Stack Overflow

programmeradmin1浏览0评论

I have created the following jsfiddle which highlights my problem. /

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.

I have created the following jsfiddle which highlights my problem. 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.

Share Improve this question edited Sep 2, 2012 at 19:40 David G 96.8k41 gold badges172 silver badges257 bronze badges asked Sep 2, 2012 at 19:38 DecrypterDecrypter 3,00012 gold badges41 silver badges60 bronze badges 1
  • It's recommended you use the array literal [] to create an array instead of new Array(); – David G Commented Sep 2, 2012 at 19:44
Add a comment  | 

5 Answers 5

Reset to default 7

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

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 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/

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

What this is changes with the scope of each function. However, myArray will be visible to inner function. Example:

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

alert(myArray); should work fine I think

发布评论

评论列表(0)

  1. 暂无评论