Internal function cannot access a variable of external functions

I 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 method. I cannot get my method to access my field variable.

+5
source share
5 answers

you tried to access a local variable using this operator, which is wrong, so here is a 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/

+6
source

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

, :

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();​

, -:

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();​
+5

You do not need this.myArray. Use myArraywill only be sufficient (and work).

+1
source

alert(myArray);should work fine. I think

+1
source

What thisare changes in the scope of each function. However, myArraythe internal function will be visible. Example:

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

All Articles