此代码位于Knockout JS视图模型中:
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
};
为什么在定时器回调中无法识别属性?看起来像是一个范围问题,但我似乎无法解决它。
答案 0 :(得分:2)
您应该阅读Javascript scopes和the var self = this
idiom。 this
关键字在回调函数中可能会出现意外行为,因为它可能设置为意外(例如调用超时回调的函数,或window
或...)。
类似*这将是您问题的直接解决方案:
myViewModel.prototype.func1 = function()
{
var self = this;
alert(self.prop1()); //works fine here
myTimer = setTimeout(function() {
alert(self.prop1());
}, 3000);
};
*“喜欢”这个,因为你的问题没有代码来实际重现你的问题;一个repro在帮助你解决问题方面会更有用