Search code examples
javascriptdomfunctionmootoolsthis

Scope of THIS keyword in Function?


Should 'this' in the following code not still refer to the DOM object selected by the MooTools selector?

$$('div').addEvent('click', function()
{
    var click1 = function(){$(this).setStyle('background', 'red');}
    click1();
});

Solution

  • You'll need to do this instead to refer to the element you want:

    click1.call(this);
    

    Otherwise this refers to window inside the function, you can see the working version here.