0

In the init function of the myFeature object below there is the line $.extend(myFeature.config, config). My background makes me wonder why the line isn't $.extend(this.config,config)? Wouldn't this refer to the parent object in the body of the function?

If that is not the case, I think I would want to use the revealing module pattern, if I understand it well enough, because I can do var self = this; and refer to self throughout the properties of myFeature. I don't understand how in the object literal pattern the init property has access to myFeature within the function. It seems myFeature is globally scoped and all its properties and itself can be accessed by anyone at anytime, I know this is the nature of javascript and I understand a bit but I am thinking the revealing module pattern will give me private/public access that makes me sleep better at night.

var myFeature = {
    config : {
        wrapper : '#myFeature',
        container : 'div',
        urlBase : 'foo.php?item='
    },

    init : function(config) {
        $.extend(myFeature.config, config);
        $(myFeature.config.wrapper).find('li').
            each(function() {
                myFeature.getContent($(this));
            }).
            click(function() {
                myFeature.showContent($(this));
            });
    },

    buildUrl : function($li) {
        return myFeature.config.urlBase + $li.attr('id');
    },

    getContent : function($li) {
        $li.append(myFeature.config.container);
        var url = myFeature.buildUrl($li);
        $li.find(myFeature.config.container).load(url);
    },

    showContent : function($li) {
        $li.find('div').show();
        myFeature.hideContent($li.siblings());
    },

    hideContent : function($elements) {
        $elements.find('div').hide();
    }
};

$(document).ready(function() { myFeature.init(); });
Brian Ogden
  • 18,439
  • 10
  • 97
  • 176

1 Answers1

0

I wonder why $.extend(myFeature.config, config) isn't $.extend(this.config,config)? Wouldn't this refer to the parent object in the body of the function?

Yes, since you're calling it with myFeature.init() it would work - see how this works. However, you can strife for safety - by explicitly refering to myFeature it would also allow

$(document).ready(myFeature.init);

I don't understand how in the object literal pattern the init property has access to myFeature within the function. It seems myFeature is globally scoped and all its properties and itself can be accessed by anyone at anytime.

Yes. The myFeature variable is in global scope and could even be overwritten by a completely different object. The reavealing module pattern would have a local-scoped self variable, which could not be manipultated.

I am thinking the revealing module pattern will give me private/public access that makes me sleep better at night

Yes. If you like it better, you should implement it :-)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375