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.
The call hasn't finished yet. Set it to run in the next cycle:
http://fiddle.jshell.net/gWUD9/
You can use
this
to access the callback in the context of the newly create object, andcall
to invoke the callback.You could try this:
newMyObject
is not aware ofnewMyObject
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 bynew myObject
wont exist yet.newMyObject
will be undefined when it is executed by the statementcallback();
, which runs the following code: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.