Not able to access 'this' in an 'each' within a Class.create
I have the following code snippet. It is confusing, because I can't seem to access 'this' within the each.
The used JavaScript library is 开发者_运维技巧Prototype.
MyClass = Class.create({
initialize : function(options) {
this.testmsg = 'Hi!';
alert(this.testmsg); // Here it is 'Hi!'
var elements = $$('img');
elements.each(function(element) {
alert(this.testmsg); // Here it is 'undefined', even though I bind 'this'
}).bind(this);
}
});
I might be doing something horribly wrong, but I can not just figure out what that is.
How can I access 'testmsg' within the each - while using 'Class.create'?
XD... small (but important) mistake.
elements.each(function(element) {
alert(this.testmsg); // Here it is 'undefined', even though I bind 'this'
}.bind(this));
you must bind the inside function, not the each function
Good Luck
this is because this referrs in your case to the element in the each loop.
you can resolve that problem by changing your class a bit (not-tested):
MyClass = function(){
var that = this;
this.testmsg = 'Hi!';
alert(this.testmsg); // Here it is 'Hi!'
elements.each(function(element) {
alert(that.testmsg); // Here it is 'Hi!'
});
}
You could solve this by creating a variable self
which refers to this
in the top of your initialize
function.
MyClass = Class.create({
initialize : function(options) {
var self = this; // Create a reference to 'this'
this.testmsg = 'Hi!';
elements.each(function(element) {
alert(self.testmsg);
});
}
});
Because this
in the closure points to the function's this which I believe is jquery object.
Solution is to store this
in a var
:
MyClass = Class.create({
initialize : function(options) {
this.testmsg = 'Hi!';
var that = this;
alert(this.testmsg); // Here it is 'Hi!'
var elements = $$('img');
elements.each(function(element) {
alert(that.testmsg); // Here it is 'undefined', even though I bind 'this'
}).bind(that);
}
});
精彩评论