Mottie
Mottie

Reputation: 86443

Is it possible to reference object within the same object?

I've been messing around with jQuery plugin code and I'm trying to put all of my common variables into a single object for easy access. I have included a few examples below on how I've done this, but I'm wondering how others deal with this problem.

Lets say I have this

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

What I'm trying to do is use the ulist object in as a base, then find the number of li's

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 this:

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 samples are just thrown together, and only meant to get the idea across to you. Anyway, is there a better way to do this?

Upvotes: 2

Views: 322

Answers (2)

user113716
user113716

Reputation: 322562

I would say this version that you posted, but no need to initialize listLen to 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 would work too, but no need to do two calls to $.extend(). It can accept more than one object.

$.extend(options, defaults, defaults2);

Your first solution still seems better.


EDIT:

(As pointed to, you can use a function. Although I'd still assign the function outside the initialization of the defaults object, so you can add the function call operator () at the end, and call it like 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 like a property and get the result of the function call, sort of like calling .length on a jQuery object.

Upvotes: 1

Sean O
Sean O

Reputation: 2619

The jQuery plugin development pattern by Mike Alsup is a few years old, but has aged well, and is still a great starting point for plugin development.

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

Upvotes: 0

Related Questions