jQuery: plugin methods and properties

by gabrieleromanato

HTML

<div id="test"></div>

CSS

#test {
    width: 100px;
    height: 100px;
    background: green;
    margin: 1em;
}

JavaScript

(function($) {
    $.fn.plugin = function(options) {

        var self = this;
        var defaults = {
            test: 'Foo',
            bar: 'Baz'
        };

        options = $.extend(defaults, options);


        self.property = 'Test';
        self.method = function() {
            console.log(self.property);
            console.log('Method called');
        }



        return self.each(function() {
            self.property = options.test + ' ' + options.bar;

            $(self).on('click', self.method);

        });
    };
})(jQuery);

$('#test').plugin(); // 'Foo Baz' 'Method called'
console.log($('#test').plugin().property); // 'Foo Baz'