Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner function cannot access outer functions variable

Tags:

javascript

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.

like image 682
Decrypter Avatar asked Sep 02 '12 19:09

Decrypter


2 Answers

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();​
like image 160
Raymond Chen Avatar answered Sep 21 '22 10:09

Raymond Chen


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/

like image 38
Saket Patel Avatar answered Sep 19 '22 10:09

Saket Patel