0

我有这个类结构(或多或少):

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

我对 Javascript 很陌生,现在还没有太多的细节,但这对我来说似乎很奇怪。当 onchange 事件触发时,它会调用 onchangelistener。为什么 this.apiSelect 未定义?我的意思是我已经为它增加了价值。

我当前的代码看起来像这样

4

2 回答 2

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

内部onchangelistener函数的引用thisthis外部范围内的引用不同。所以你需要创建一个对外部this(with var self = this;)的引用并在函数内部使用它

于 2012-09-19T14:41:58.917 回答
0
Page = function () {
        var apiSelect = null;
        this.onchangelistener = function () {
            console.log(apiSelect);
        };
        ...
};

发生这种情况是因为this被绑定到新的“内部”函数并且它不知道apiSelect数据成员是什么。

于 2012-09-19T14:43:09.313 回答