Reputation: 3016
I'm using John Resig's class inheritance (for JavaScript) script. It allows you to define "classes" that you can inherit from. I've found one limitation: I cannot reference the class structure/base class (this) from within nested functions.
For example
var myclass = anotherclass.extend({
dostuff: function() {
$('#myelem').animate({ top: 100 }, function() { this.saystuff('Done'); });
},
saystuff: function(Message) {
alert(Message);
}
});
var foo = new myclass();
foo.dostuff();
When the script calls the callback which in turns calls this.saystuff
it tries to call a method for the unnamed function I'm wrapping the callback in, so I can't call up the chain of functions.
The only way I've found to get around this it to call the variable that created the object, but that's not a good idea since that variable name should be able to change at any time.
Any help would be appreciated.
Upvotes: -1
Views: 68
Reputation:
The "base class" isn't inherently inaccessible. The problem is that the this
keyword is simply repurposed within every new nested scope to refer to a different context. Within the callback you are passing to animate
, this
refers to the jQuery collection wrapping your element.
One way to get around this is to capture the context in a variable and enclose it in the callback:
dostuff: function() {
var that = this;
$('#myelem').animate({ top: 100 }, function() { that.saystuff('Done'); });
}
Upvotes: 2
Reputation: 207557
It is out of scope.
dostuff: function() {
var that=this;
$('#myelem').animate({ top: 100 }, function() { that.saystuff('Done'); });
},
and looks like you are using jQuery which has proxy
dostuff: function() {
$('#myelem').animate({ top: 100 }, $.proxy(this, this.saystuff, 'Done'); });
},
Upvotes: 4