0

I have this class structure (more or less):

function DataLoader = function () {
    this.setup = function () {
        this.page = new Page();
        this.page.setup();
    };

    Page = function () {
        this.apiSelect = null;
        this.onchangelistener = function () {
            //---------------- look here ---------------
            console.log(this.apiSelect); //Why is this.apiSelect undefined?
            //---------------- look here ---------------
        };

        this.setup = function () {
            this.apiSelect = document.getElementById("foo");
            //This is also weird to me, I had to do it like this
            //to get the functionality I wanted...
            document.getElementById("foo").onchange = this.onchangelistener;
        };
    };
};

var dl = new DataLoader();
dl.setup();

I am very new to Javascript and don't now much of the nitty gritty details yet, but this seems very strange to me. When the onchange event fires it calls onchangelistener. How come that this.apiSelect is undefinded? I mean i have allready added a value to it.

My current code looks like this

Daniel Figueroa
  • 10,348
  • 5
  • 44
  • 66

2 Answers2

1
 ...
 Page = function () {
        var self = this;
        this.apiSelect = null;
        this.onchangelistener = function () {
            console.log(self.apiSelect);
        };

inside onchangelistener function the reference of this is not the same of this in the outer scope. So you need to create a reference to the outer this (with var self = this;) and use it inside the function

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0
Page = function () {
        var apiSelect = null;
        this.onchangelistener = function () {
            console.log(apiSelect);
        };
        ...
};

This was happening because this was being bound to the new 'internal' function and it had no idea what the apiSelect data member was.

Jordan Arsenault
  • 7,100
  • 8
  • 53
  • 96