我有一个使用原型链调用一些异步函数的Object:
function Wow() {
this.myAsyncFunction();
}
Wow.prototype.myAsyncFunction = function() {
// Once my async function is complete, I fire a callback
this.completed(); // Does not work
}
我想像这样使用它:
var wow = new Wow();
wow.completed = function() {
alert('Awesome');
}
这是我创建的代码片段,用于模拟我的想法。
function Wow() {
this.ok = document.getElementById('ok');
this.wait();
}
Wow.prototype.wait = function() {
this.ok.innerHTML = "Waiting..."
window.setTimeout(function() {
this.completed();
}, 1000);
}
var wow = new Wow();
wow.completed = function() {
wow.ok.innerHTML = "Compelted";
};

#ok {
font-size: 28px;
color: red;
}

<div id="ok"></div>
&#13;
我花了一个多小时搜索谷歌和StackOverflow寻求解决方案,但我发现甚至难以搜索它。
答案 0 :(得分:0)
代码的问题是this
在嵌套函数中没有继承。
这有效:
Wow.prototype.wait = function() {
this.ok.innerHTML = "Waiting...";
var that = this;
window.setTimeout(function() {
that.completed();
}, 1000);
}
function Wow() {
this.ok = document.getElementById('ok');
this.wait();
}
Wow.prototype.wait = function() {
this.ok.innerHTML = "Waiting...";
var that = this;
window.setTimeout(function() {
that.completed();
}, 1000);
}
var wow = new Wow();
wow.completed = function() {
wow.ok.innerHTML = "Compelted";
};
&#13;
#ok {
font-size: 28px;
color: red;
}
&#13;
<div id="ok"></div>
&#13;
答案 1 :(得分:0)
您需要稍微更改wait
函数,this
运行代码时setTimeOut
不可用,因为该代码不在上下文中this
:
Wow.prototype.wait = function() {
var self = this;
this.ok.innerHTML = "Waiting..."
window.setTimeout(function() {
self.completed();
}, 1000);
}