0

I have a JS file with this object setup amount other objects.

     if (!me) var me = {};

        me.page = {


            initialize:function( options ) {
                var settings = $.extend({
                    error_module: $('#error-module'),
                    mainForm: $('form')
                }, options);

            },
            pagemaker:function(){
               var temp = settings.error_module
            }
        }

        me.bla = {
          // the scope of bla
        }

if I call me.page.pagemaker() it can't find the settings variable. I don't want to make settings global I want it to be in scope with the object page. How can I make this work so var temp = settings.error_module is not undefined.

1
  • FYI var me = me || {} Commented Jan 7, 2014 at 23:48

3 Answers 3

2

You can use an IIFE (Immediately Invoked Function Expression). See if this helps. I slightly modified your code to what I would consider best practice:

var me = me || (function(){
  var settings = {
    errorModule: '#error-module',
    mainForm: 'form'
  };
  return {
    page: {
      init: function(options) {
        $.extend(settings, options);
      },
      pageMaker: function() {
        var temp = $(settings.errorModule);
      }
    },
    bla: function() {

    }
  };
}());

Edit: Missed the outer object.

Sign up to request clarification or add additional context in comments.

Comments

1

Make it a property of me:

initialize:function( options ) {
    me.settings = ...;

}

And later:

pagemaker:function(){
   var temp = me.settings.error_module
}

You also have a scope problem here:

if (!me) var me = {};

You could use this instead:

var me = me || {};

Comments

0

If you want to keep it within the scope of the object page, you can define another attribute called settings in your page object since it's just represented by keys and values, like so:

me.page = {

  // Initial/default values
  settings: {
    error_module: null,
    mainForm: null,
  },

  initialize: function(options) {
    this.settings = $.extend({...}, options);
  },

  pagemaker: function() {
    var temp = this.settings.error_module;
  }
}

1 Comment

This.settings is showing as undefined. The only way I can get to it from another method inside me.page is by using. me.page.settings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.