<分区>
我最近尝试创建一个这样的对象:
var carousel = {
$slider: $('#carousel1 .slider'),
panes: carousel.$slider.children().length
};
我的意图是通过在对象属性中缓存 $('#carousel1 .slider')
的结果来提高 jQuery 选择器的性能,并保持代码简洁和相对 DRY。
然而,这并没有奏效。当代码执行时,它在尝试解析 panes
的值时抛出异常,提示 carousel
未定义。
这是有道理的,因为我假设 carousel
在赋值语句完全执行之前没有完全声明。但是,我想避免诉诸于此:
var carousel = {};
carousel.$slider = $('#carousel1 .slider');
carousel.panes = carousel.$slider.children().length;
这并没有太糟糕,但是 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');
})();
和
// 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;
假设这些都是正确的(我还没有测试过),这是一个艰难的决定。我想我稍微更喜欢 Matthew Flaschen 的方法,因为代码包含在一个更类似于对象声明的结构中。最终也只创建了一个变量。然而,那里有很多 this
,这似乎是重复的 - 尽管这可能只是要付出的代价。