I have below code
http://jsfiddle.net/qhoc/SashU/1/
var Callback = function(op) {
this.callback = op.callback;
}
var Test = function (op) {
for (var option in op) {
if (!this[option]) this[option] = op[option];
}
}
Test.prototype.init = function(bb) {
console.log('aa = ' + this.aa);
console.log('bb = ' + bb);
if (bb < 3) {
this.init(bb + 1);
} else {
this.callback;
}
}
var finalCallback = function() {
console.log('this is finalCallback');
}
var myCallback = new Callback({
callback: finalCallback
});
var myTest = new Test({
aa: 1,
callback: myCallback
});
myTest.init(1);
Line 19 didn't print 'this is finalCallback' AT ALL because this.callback; got executed but it doesn't point to a function. But the below works:
myTest.init(1);
myCallback.callback();
I guess when passing myCallback to myTest, it didn't pass finalCallback??
Can someone help to explain this behavior and how to fix it?
this works:
var myTest = new Test({
aa: 1,
callback: myCallback.callback()
});
I assume this is the bit you mean. If not, please clarify what is not printing.
this doesn't work, because it is only a reference - an assignment.
callback: myCallback
this is what executes it ()
so:
callback: myCallback.callback;
then:
this.callback();
I apologize if I am not succinct enough. I hope I am understanding what you are asking.
seems you want to make this (use op.callback as function ):
var Callback = function (op) {
this.callback = op.callback;
return this.callback;
};
and functions should be invoked with ()
} else {
this.callback();
}
As has been pointed out, you're not even trying to invoke this.callback on line 19. Invoke it with parentheses.
Even then, it doesn't work. When you do var myTest = new Test({
aa: 1,
callback: myCallback
});, myCallBack isn't a function; it's an object with a property callback. Change line 19's this.callback to this.callback.callback() to invoke that function. One line 19, this.callback is an instance of Callback—an object with a property callback that is a function.
http://jsfiddle.net/trevordixon/SashU/4/ shows a working example.