![](/img/trans.png)
[英]Javascript with Jquery Mobile not working in Android 2.3 and lower
[英]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
。)因此,當您不使用bind
, this
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.