JavaScript异步问题如何解决

//下面代码存在两个问题,只允许修改Obj构造函数及其原型使程序正常执行
function initData(callback){
    setTimeout(()=>{
        callback("hello")
    },2000)
}

function Obj(){
    this.o = null  ;
    this.init(); 
}
Obj.prototype = {
    
    init :function(){
        initData(this.callback)
    },
    callback:function(name){
        this.o = {"name":name};  //问题2,此时this指向的是window对象,如何指向通过Obj产生的实例
    },
    getName:function(){
        return this.o.name;
    }
}

var obj = new Obj();
obj.getName(); //问题1,这里会报错 
 
 
----------------------------------------------------------------------------------
解决方案
 function initData(callback,that) {
                setTimeout(() => {
                    callback.call(that,"hello")
                }, 2000)
            }

            function Obj(loaded) {
                this.o = null;
                this.loaded = loaded;
                this.init();
            }
            Obj.prototype = {

                init: function () {
                    initData(this.callback,this)
                },
                callback: function (name) {
                    this.o = { "name": name };  //问题2,此时this指向的是window对象,如何指向通过Obj产生的实例
                    typeof this.loaded =="function" && this.loaded();
                },
                getName: function () {
                    return this.o.name;
                }
            }
            
            var obj = new Obj(afterLoaded);
            function afterLoaded(){
                console.log(obj.getName()); 
            }
posted @ 2020-03-26 10:58  tooSimple_sz  阅读(304)  评论(0编辑  收藏  举报