JavaScript对象属性是否可以引用同一对象的另一个属性?

Bun*_*gle 63 javascript properties declaration object variable-assignment

我最近尝试创建这样的对象:

var carousel = {
      $slider: $('#carousel1 .slider'),
      panes: carousel.$slider.children().length
    };
Run Code Online (Sandbox Code Playgroud)

我的意图是通过缓存$('#carousel1 .slider')对象属性的结果来提高jQuery的选择器性能,并保持代码简洁和相对干燥.

但是,这不起作用.当代码执行时,它在尝试解析值时抛出异常panes,抱怨carousel未定义.

这是有道理的,因为我假设carousel在赋值语句完全执行之前没有完全声明.但是,我想避免诉诸于此:

var carousel = {};
carousel.$slider = $('#carousel1 .slider');
carousel.panes = carousel.$slider.children().length;
Run Code Online (Sandbox Code Playgroud)

这并没有太糟糕,但是carousel对象将有更多依赖于其他属性值的属性,因此很快就会变得冗长.

我尝试过使用this,但无济于事.我可能没有正确使用它,或者这可能不是一个有效的方法.

对象的属性是否有一种方法可以引用同一对象的其他属性,而该对象仍然被声明?


基于Matthew Flaschen和casablanca的答案(谢谢,伙计们!),我认为这些是我最终得到的实际代码的版本,基于每种方法:

// Matthew Flaschen

var carousel = new (function() {
  this.$carousel = $('.carousel');
  this.$carousel_window = this.$carousel.find('.window');
  this.$carousel_slider = this.$carousel.find('.slider');
  this.$first_pane = this.$carousel.find('.slider').children(':first-child');
  this.panes = this.$carousel_slider.children().length;
  this.pane_gap = this.$first_pane.css('margin-right');
})();
Run Code Online (Sandbox Code Playgroud)

// casablanca

var $carousel = $('.carousel'),
    $carousel_slider = $carousel.find('.slider'),
    $first_pane: $carousel.find('.slider').children(':first-child');

var properties = {
  $carousel_window: $carousel.find('.window'),
  panes: $carousel_slider.children().length,
  pane_gap: $first_pane.css('margin-right')
};

properties.$carousel = $carousel;
properties.$carousel_slider = $carousel_slider;
properties.$first_pane = $first_pane;
Run Code Online (Sandbox Code Playgroud)

假设这些都是正确的(我没有测试过它们),这是一个艰难的电话.我认为我稍微偏爱Matthew Flaschen的方法,因为代码包含在一个更接近于对象声明的结构中.最终也只创建了一个变量.然而,那里有很多this,这似乎是重复的 - 虽然这可能只是付出的代价.

Mat*_*hen 50

不是对象文字(this在构造它之前做的文字时具有相同的值).但你可以做到

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

这使用从匿名函数构造函数创建的对象.

请注意$slider并且panes是公开的,因此可以作为carousel.$slider等访问.


cas*_*nca 19

很不幸的是,不行.该{}语法发起新对象的创建,但直到被创建的对象,它没有分配给carousel变量.此外,该this值只能作为函数调用的结果而更改.如果你的"更多属性"都只依赖于slider,那么你可以使用这样的东西:

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