开发者

Scope of THIS keyword in Function?

开发者 https://www.devze.com 2023-01-12 22:36 出处:网络
Should \'this\' in the following code not still refer to the DOM object selected by the MooTools selector?

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).setSty开发者_如何学编程le('background', 'red');}
    click1();
});


You should do it the MooTools way - by binding this to the click1 function - http://jsfiddle.net/oskar/7EArh/5/

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

Also this is already extended with MooTools methods, so there is no need for doing $(this).


The cleanest way to handle it is this:

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

$$('div').addEvent('click', click1);

in the above, 'this' get's passed to the function called.

Working example: http://jsfiddle.net/gT5dc/


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.


No. click1() isn't associated with any object (it's not e.g. callable as obj.click1()), so in it this refers to the window.

However, you can do:

click1.call(this);

The call method basically sets this to its first parameter.


In this kind of crazy situation, I just do:

$$('blah').addEvent('click', function() { var self = this;

var click1 = function(){ self.setStyle(....); }
click1();

});

... of course. mostly none of my code would include a click1(); at the end. These kind of inner functions like click1 would normally be used for some other purpose. for e.g.

var click1 = function(){ self.addClass('blah2').removeClass('blah'); } self.set('tween', { onComplete: click1 }).fade('in');

0

精彩评论

暂无评论...
验证码 换一张
取 消