javascriptjqueryjquery-ui-widget-factoryjquery-ui-widget

Do I need to define 'self', 'element' etc. at the start of every function within a JQuery Widget


I create JQuery Widgets something like this

<script type="text/javascript">
(function ($) {
        $.widget("cb.bacon", {
            _create: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code

            },

            _bacon: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            },

            _smokey: function() {
                var self = this,
                    o = self.options,
                    el = self.element;

                 // Some code
            } 
        });
    })(jQuery);                 
</script>

I invariably end up having to declare self, options, element in each function that I create.

Is there some fundimental understanding that I'm missing or do I really have to do that all the time?


Solution

  • You don't have to do that at all, that is only to make it easier to access those inside the function.

    The self variable is useful when you are using a callback in a jQuery function, where this would be set to the element that you are acting upon. For example:

    $('.bacon').each(function(){ $(this).css('background', self.getBackground()); });
    

    The variables o and el just makes for less typing. If you have the varaible self, or the reference this unchanged, you can access the options and element properties from the object directly.