簡體   English   中英

Android 2.3上的JavaScript –“此”無法正常工作嗎?

[英]JavaScript on Android 2.3 – “this” not working?

我有一堂課,結構像這樣

function myClass () {
    this.varA = 0;
}

myClass.prototype.consts = {
    someConst : 1,
    anotherConst : 1000,
}

myClass.prototype.startIt = function () {
    window.setTimeout(this.brokenFunc.bind(this), this.consts.anotherConst);
}

myClass.prototype.brokenFunc = function () {
    this.varA += this.consts.someConst;

    window.setTimeout(this.brokenFunc.bind(this), this.consts.anotherConst); 
}

// Example call
var myObj = new myClass();
myObj.startIt();

這在大多數Android設備上都可以正常工作-但運行Android 2.3的用戶現在通知我它不起作用,我可以在模擬器中重現該錯誤。 首先,它說TypeError: Result of expression 'this.brokenFunc.bind' [undefined] is not a function此行TypeError: Result of expression 'this.brokenFunc.bind' [undefined] is not a function (在startIt內):

window.setTimeout(this.brokenFunc.bind(this), this.consts.anotherConst); 

我想,這很公平,並且做了舊的var _this = this技巧來繞開bind調用。 但現在它說TypeError: Result of expression 'this.consts' [undefined] is not an object在此行中TypeError: Result of expression 'this.consts' [undefined] is not an object

this.varA += this.consts.someConst;

我有點迷路了。 這一段代碼怎么不起作用? 特別是因為它適用於大多數Android版本。

默認情況下, setTimeout調用函數與this全局對象(即window ,在瀏覽器中)。 (請注意:在嚴格模式下,它是undefined 。)因此,當您不使用bindthis brokenFunc現在是window而不是注冊超時的對象。

為了從startIt保留this startIt ,您需要將調用包裝在匿名函數中:

myClass.prototype.startIt = function () {
    var that = this;

    window.setTimeout(function() {
        // call brokenFunc with the outer this
        that.brokenFunc();
    }, this.consts.anotherConst);
}

發生第一個錯誤是因為Android 2.3瀏覽器不支持EMCAScript 5 bind功能。 出現第二個錯誤是因為this.consts實際上是window.consts ,它不存在。 只是包裝在具有匿名函數調用that在它的范圍,並要求從功能上that

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM