我是JS的新手,我正在编写的脚本要求我使用ajax从API检索JSON数据。这意味着我必须了解回调等等。
我对以下简化代码的目标是调用一个函数(MethodA),然后调用MethodB,它在完成时调用MethodC。
出于某种原因,MethodC无法激活,我不明白为什么。
请参阅实例示例:https://jsfiddle.net/Hoppertron/mtpem1r2/5/
(我知道我可能会使用jQuery的延迟when().then()
模式或ES6 Promises,但作为一个学习练习,我试图让我的头脑绕着准系统的方式去做。)
var Item = function (prop1, prop2, prop3) {
this.prop1 = prop1,
this.prop2 = prop2,
this.prop3 = prop3,
this.prop4; //<----------------- Notice I'm not setting this yet.
}; // I'm setting it in MethodB.
// Is this stupid?
Item.prototype.MethodA = function() {
console.log("starting A")
this.MethodB(function () {this.MethodC}); //<----- Why doesn't MethodC run?
};
Item.prototype.MethodB = function(callback) {
console.log("starting B")
this.prop4 = "I'm prop 4";
console.dir(this);
callback();
};
Item.prototype.MethodC = function () {
console.log("starting C")
document.getElementById("MainDiv").innerHTML = this.prop4;
};
var MyItem = new Item("I'm prop 1","I'm prop 2","I'm prop 3");
try {
MyItem.MethodA(); //<-- Should call MethodA which calls MethodB which calls MethodC
}
catch(err) {
document.getElementById("MainDiv").innerHTML = err;
};