0
此代碼是在KnockoutJS視圖模型:KnockoutJS:功能範圍錯誤
function myViewModel()
{
this.prop1 = ko.observable(123);
this.prop2 = ko.observable("Hello");
..
..
}
myViewModel.prototype.func1 = function()
{
alert(this.prop1()); //works fine here
myTimer = setTimeout(function()
{
alert(this.prop1()); //this.prop1() raises an undefined error
}, 3000); //from console: Uncaught TypeError: undefined is not a function
};
爲什麼沒有財產的計時器回調中識別?看起來像一個範圍問題,但我似乎無法解決它。
你好Jeroen,並感謝一百萬;它做到了。你建議我在另一篇文章中閱讀JavaScript範圍,但遺憾的是,我沒有。我從來沒有完全理解self關鍵字。非常感謝你。 – iSofia 2014-10-28 08:09:17
很高興幫助。即使你沒有時間閱讀它(這是一個密集的話題),只要記住始終用'var self = this;'開始你的視圖模型構造函數,並且在所有地方都使用'self'而不是'this',你將會倖免於難。 – Jeroen 2014-10-28 08:14:47
我一定會那樣做。感謝您的提示和解決方案。你是一個拯救生命的人,Jeroen。 – iSofia 2014-10-28 08:39:26