I have a small problem with a object that uses jquery. since jquery overwrites the this pointer I cant call my sub methods without resorting to save the this pointer in a that variable is this a preferred way or is there a better solution? Is there a way to save the this pointer in the object ( like a class method with another name ) ?
Trying to learn javascript with javascript the good parts but I dont think I understand all the quirks yet :).
//from javscript the good parts
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
var Tester = {
printData: function (text) {
console.log(text)
},
start: function () {
var that = this;
jQuery('id').click(function () {
that.printData('firstColumn')
});
}
};
var test = Object.create(Tester)
test.start()
Best Regards Anders Olme guess this is similiar to Overwritten "this" variable problem or how to call a member function?
In general, yes, that's what you have to do.
In this specific case, jQuery provides you some help.
jQuery('id') // <-- should be #id ?
.bind('click', { myThing : this }, function (e) {
e.data.myThing.printData('firstColumn');
})
;
See the docs for bind()
. Internally, jQuery is just doing the exact same thing as you're doing there, so it won't make any significant difference in terms of performance, but it might make your code a bit more manageable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With