Javascript Callbacks With Object Constructor
Solution 1:
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);
}
functioncaller(){
var newMyObject = newmyObject(function() {
alert(this.accounts[1]);
});
}
Solution 2:
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 = newmyObject(function() {
alert(newMyObject.accounts[0]);
});
Solution 3:
You could try this:
functionApplication () {
varself = this;
myObject = function(callback){
var tmpThis = this;
this.accounts = [];
tmpThis.accounts[0] = 1;
tmpThis.accounts[1] = 2;
callback();
};
functioncaller(){
self.newMyObject = new myObject(function() {
alert(self.newMyObject.accounts[1]);
});
}
}
Solution 4:
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.
Post a Comment for "Javascript Callbacks With Object Constructor"