【发布时间】:2011-02-14 10:21:29
【问题描述】:
我的 JS 代码大致是这样的:
function myObject()
{
this.a = 13;
this.fetchData = function()
{
alert(this.a);
getData(this.processData);
}
this.processData = function(data)
{
// do stuff with data
alert(this.a);
}
this.fetchData();
}
function getData(callback)
{
// do async request for data and call callback with the result
}
我的问题是:函数 fetchData 可以通过 this 关键字访问我的 a 变量,但另一个函数 processData 在被 getData 调用时不会。我了解为什么会发生这种情况,但不知道如何解决。
您将如何最好地以 OOP 风格解决这个问题? (函数 getData 必须可用于多个类)
【问题讨论】:
标签: javascript oop asynchronous coding-style