javascript - Assign this to self in jQuery UI - Stack Overflow

admin2025-04-20  0

I am currently writing a jQuery UI plugin and investigate therefore the existent jQuery UI sources. In the _create method of the accordion plugin this is assigned to self (link to source), but then both this and self are used side by side in that method. So why do they chose to assign to self at all?

I am currently writing a jQuery UI plugin and investigate therefore the existent jQuery UI sources. In the _create method of the accordion plugin this is assigned to self (link to source), but then both this and self are used side by side in that method. So why do they chose to assign to self at all?

Share Improve this question asked Nov 5, 2010 at 17:39 medihackmedihack 16.6k21 gold badges91 silver badges140 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

It's all about the context. In the function itself self and this refer to the same object but in the event handlers this refers to the DOM element the event is targeting. By assigning the value of this to self it leaves them free to refer to either the widget object or to the DOM element within those event handlers.

If you look closely you'll notice that within the context of the function they use self exclusively and while in the anonymous functions (event handlers) they use both this and self to refer to the DOM element or to the Widget, respectively.

I don't exactly know how JQuery UI plugins work, but what I could imagine is the following scenario. I think they wanted to keep a reference to the Widget object without overwriting this (changing the scope). When the function is executed the scope is no longer the Widget object but a DOM Element. Therefore they can easily add classes and everything using this as a reference. Before that happens they rescue the widget objcet scope using closure and assigning the value of this (now still being the widget object, when the code is interpreted) to the local variable self. Now using self they can change fields on the object.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114442a285778.html

最新回复(0)