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.
you must bind the inside function, not the each function
Good Luck