原型链回调

时间:2014-10-05 20:48:11

标签: javascript

我有一个使用原型链调用一些异步函数的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;
&#13;
&#13;

我花了一个多小时搜索谷歌和StackOverflow寻求解决方案,但我发现甚至难以搜索它。

2 个答案:

答案 0 :(得分:0)

代码的问题是this在嵌套函数中没有继承。

这有效:

Wow.prototype.wait = function() {
    this.ok.innerHTML = "Waiting...";
    var that = this;
    window.setTimeout(function() {
        that.completed();
    }, 1000);
}

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:0)

您需要稍微更改wait函数,this运行代码时setTimeOut不可用,因为该代码不在上下文中this

Wow.prototype.wait = function() {
    var self = this;
    this.ok.innerHTML = "Waiting..."
    window.setTimeout(function() {
        self.completed();
    }, 1000);
}

工作样本 - http://jsfiddle.net/4xcjhe8d/2/