Is it possible to reference an object within one object?

I've been messing around with jQuery plugin code and I'm trying to put all my shared variables into one object for easy access. I've provided some examples below on how I did it, but I'm wondering how others have dealt with this problem.

Let's say I have it

var x = function(options){
 var defaults = {
  ulist   : $('ul#list'),
  listLen : $('ul#list').children().length
 }
 $.extend(options, defaults);
 // do other stuff
}

      

What I am trying to do is use an object ulist

as a base, then find the numberli

I guess I could do this:

var x = function(options){
 var defaults = {
  ulist   : $('ul#list'),
  listLen : 0
 }
 defaults.listLen = defaults.ulist.children().length;
 $.extend(options, defaults);
 // do other stuff
}

      

or that:

var x = function(options){
 var defaults = {
  ulist : $('ul#list')
 };
 var defaults2 = {
  listLen : defaults.ulist.children().length
 }
 $.extend(defaults, defaults2);
 $.extend(options, defaults);
 // do other stuff
}

      

The above code examples are just dumped together and are only intended to convey the idea to you. Anyway, is there a better way to do this?

+2


a source to share


2 answers


I would say this version you posted, but doesn't need to be initialized listLen

before 0

.

var x = function(options){
 var defaults = {
  ulist   : $('ul#list'),
  listLen : 0    // Remove this line
 }
 defaults.listLen = defaults.ulist.children().length;
 $.extend(options, defaults);
 // do other stuff
}

      


EDIT:

Your second solution will work too, but you don't need to make two calls $.extend()

. It can accept more than one object.

$.extend(options, defaults, defaults2);

      



Your first solution still seems to be better.


EDIT:

(As pointed out, you can use a function. Although I did assign the function outside of the object initialization defaults

, so you can add a function call statement ()

at the end and call it as a property.

var x = function(options){
    var defaults = {
        ulist: $('ul#list')
    } 

    defaults.listLen = function() {return defaults.ulist.children().length}();
}

      

Now you can access defaults.listLen

as a property and get the result of a function call, like calling .length

a jQuery object.

+1


a source


The jQuery Plugin Development Pattern by Mike Alsup is a few years old, but it does the job well and is still a great starting point for plugin development.



http://www.learningjquery.com/2007/10/a-plugin-development-pattern

0


a source







All Articles