Javascript Callbacks with Object constructor

2019-07-15 14:31发布

Following is a function which creates and object and call the callback (not the exact code but something similar).

myObject = function(callback){

    var tmpThis = this;
    this.accounts = [];
    tmpThis.accounts[0] = 1;
    tmpThis.accounts[1] = 2;
    callback();
}

function caller(){
    var newMyObject = new myObject(function() {
        alert(newMyObject.accounts[1]);
    }); 
}

newMyObject is undefined inside the callback function. Is there a way I can access it. I read similar questions but none simply explains why.

I can fix it by passing back the created object in a second parameter to the callback function. But I think its a hack rather than the proper way.

4条回答
来,给爷笑一个
2楼-- · 2019-07-15 15:10

The call hasn't finished yet. Set it to run in the next cycle:

http://fiddle.jshell.net/gWUD9/

myObject = function(callback){

    var tmpThis = this;
    tmpThis.accounts = [];
    tmpThis.accounts[0] = 1;
    tmpThis.accounts[1] = 2;
    setTimeout(callback,1);
}

    var newMyObject = new myObject(function() {
        alert(newMyObject.accounts[0]);
    }); 
查看更多
一夜七次
3楼-- · 2019-07-15 15:12

You can use this to access the callback in the context of the newly create object, and call to invoke the callback.

myObject = function(callback){

    var tmpThis = this;
    this.accounts = [];
    tmpThis.accounts[0] = 1;
    tmpThis.accounts[1] = 2;
    callback.call(this);
}

function caller(){
    var newMyObject = new myObject(function() {
        alert(this.accounts[1]);
    }); 
}
查看更多
唯我独甜
4楼-- · 2019-07-15 15:12

You could try this:

 function Application () {

    var self = this;

    myObject = function(callback){

        var tmpThis = this;
        this.accounts = [];
        tmpThis.accounts[0] = 1;
        tmpThis.accounts[1] = 2;
        callback();
    };

    function caller(){
        self.newMyObject = new myObject(function() {
            alert(self.newMyObject.accounts[1]);
        }); 
    }
}
查看更多
可以哭但决不认输i
5楼-- · 2019-07-15 15:18

newMyObject is not aware of newMyObject inside of the parameter which is passed into it. It will be undefined.

In other words, when alert(newMyObject.accounts[1]); is run, newMyObject as defined by new myObject wont exist yet.

newMyObject will be undefined when it is executed by the statement callback();, which runs the following code:

function() {
  alert(newMyObject.accounts[1]);
}

Your callback function is being passed into your myObject function. You can just alert(accounts[1]) from within your myObject function.

The pattern you are attempting to use does not usually take a function callback. Usually you would pass in a object of options, which would serve to customize myObject.

It is not clear what you are trying to do.

查看更多
登录 后发表回答