5

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.

0x499602D2
  • 87,005
  • 36
  • 149
  • 233
Decrypter
  • 2,522
  • 12
  • 34
  • 54

5 Answers5

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();​
Raymond Chen
  • 42,606
  • 11
  • 86
  • 125
  • You answered this quite a while ago, but I don't think your second answer would work. In that case, 'this' is referring to the inner function, not the outer. – rjcarr Jun 13 '13 at 00:01
  • 2
    Try it. It works. That's because `this` refers to "the thing before the dot" which in this case is `exampleObj`. – Raymond Chen Jun 13 '13 at 02:57
6

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/

Saket Patel
  • 6,251
  • 1
  • 24
  • 34
1

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

Rhyono
  • 2,289
  • 21
  • 38
1

alert(myArray); should work fine I think

athspk
  • 6,576
  • 7
  • 32
  • 51
SNAG
  • 1,836
  • 2
  • 20
  • 37
1

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();​
Oliver Moran
  • 4,849
  • 3
  • 28
  • 44