Q:

How to call this in a function in a mootools class

I'm having problems implementing classes in mootools since I can't use 'this' when I send methods in say element.addEvent.
Say I have this mootools class:
var Dude = new Class({

    highlightColor: '#f00',

    doStuff: function() {
        var parent = $('theParentId');

        new Element('div', {'html': 'Click me'})
            .inject(parent)
            .addEvent('click', function(){

                new Element('div', {'html': 'you clicked'})
                    .highlight(this.highlightColor);

            });
    },

});

This code will throw exception inside the addEvent method call, because this is suddenly is in another context. Is there some other way to get the object's highlightColor (or any other member that a mootools Class may have)? 

A:

you need to bind the this reference to the function each time you use a function (on addEvents or each)
var Dude = new Class({

    highlightColor: '#f00',

    doStuff: function() {
        var parent = $('theParentId');

        new Element('div', {'html': 'Click me'})
            .inject(parent)
            .addEvent('click', function(){

                new Element('div', {'html': 'you clicked'})
                    .highlight(this.highlightColor);

            }.bind(this));
    }
});

be carefoul with the last coma on the function doStuff... firefox is like a mother it will foregive you but iexplorer is a bmf it will throw an error and wont tell you why

A:

The "MooTools way" would be to use the bindWithEvent function:
var Dude = new Class({

    highlightColor: '#f00',

    doStuff: function() {
        var parent = $('theParentId');

        new Element('div', {'html': 'Click me'})
            .inject(parent)
            .addEvent('click', function(event){

                new Element('div', {'html': 'you clicked'})
                    .highlight(this.highlightColor); // <- `this` refers to the 
            }.bindWithEvent(this));                  //    outer `this` value
    },
    //...
});

That method allows you to preserve the this value on a function, and pass additional arguments if necessary.
The first argument of the bound function, will refer to the Event object of the triggered event.

