Inner function cannot access outer functions variable

后端 未结 5 631
攒了一身酷
攒了一身酷 2021-01-13 10:14

I have created the following jsfiddle which highlights my problem. http://jsfiddle.net/UTG7U/

var ExampleObject = function() {
   var myArray = new Array();         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-13 10:39

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

提交回复
热议问题