Sander
Sander

Reputation: 1274

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'?

Upvotes: 1

Views: 72

Answers (4)

Kevin
Kevin

Reputation: 5694

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);
        });
    }
});

Upvotes: 1

pleasedontbelong
pleasedontbelong

Reputation: 20102

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

Upvotes: 2

helle
helle

Reputation: 11650

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!'
    });
}

Upvotes: 1

Aliostad
Aliostad

Reputation: 81660

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);

  }
});

Upvotes: 0

Related Questions