Can a JavaScript object property refer to another property of the same object? [duplicate]

Solution 1:

Not with object literals (this has the same value during constructing of the literal that it did before-hand). But you can do

var carousel = new (function()
{
      this.$slider =  $('#carousel1 .slider');
      this.panes = this.$slider.children().length;
})();

This uses an object created from an anonymous function constructor.

Note that $slider and panes are public, so can be accessed as carousel.$slider, etc.

Solution 2:

Unfortunately, no. The {} syntax initiates creation of a new object, but until the object is created, it is not assigned to the carousel variable. Also, the this value can only change as a result of a function call. If your "several more properties" are all going to depend only on slider, then you could get around with something like this:

var slider = $('.slider');
var carousel = {
  panes: slider.children.length(),
  something: slider.something_else,
  // ...
};
carousel.slider = slider;