I am trying to create a JavaScript object as follows.
var MyObject = function (parameters) {
this.parameters = parameters;
parameters.userFunction(this.MyObjectCallback);
}
MyObject.SOME_STATIC_VARIABLE = 21;
MyObject.prototype = {
myObjectCallback: function() {
console.log(this);
}
}
The MyObject object will accept a userFunction to which it will pass a handler. The user function will do some logic and pass the result back to the instance, for example:
new MyObject({userFunction: function(callback) {
$.post(
'http://localhost/~knyttl/source.php',
{},
callback,
'json');,
}});
Unfortunately, even though the callback is properly called, this gets an instance of the JQuery object and not of the MyObject instance as I would like. To conclude, I can not manage to keep the MyObject instance.
I am not even sure, whether this is a correct way of creating JavaScript objects. I will be grateful for any suggestion.
You can bind a specific
thisvalue using.bind. Also I corrected the capitalizing ofMy.When you call a function like
a.b(), then insideb,this === a. However, if you do not directly call it but only pass the function (likea.b) and call it later, this binding is lost..bindreturns a new function which now receives the jQuery ajax result asthis. However, it ignores that and callsmyObjectCallbackwith the predefined (bound)this..bindis not available on older browsers but there are shims available.