Development Tip

JavaScript 개체 속성이 동일한 개체의 다른 속성을 참조 할 수 있습니까?

yourdevel 2020. 11. 28. 12:32
반응형

JavaScript 개체 속성이 동일한 개체의 다른 속성을 참조 할 수 있습니까?


이 질문에 이미 답변이 있습니다.

최근에 다음과 같은 개체를 만들려고했습니다.

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반복적으로 보이는 많은 것이 있습니다.


객체 리터럴이 아닙니다 ( this리터럴을 구성하는 동안 이전에 수행 한 것과 동일한 값을 가짐). 하지만 당신은 할 수 있습니다

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

이것은 익명의 함수 생성자에서 생성 된 객체를 사용합니다.

참고 $sliderpanes공공, 그래서으로 액세스 할 수있다 carousel.$slider


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;

참고URL : https://stackoverflow.com/questions/3173610/can-a-javascript-object-property-refer-to-another-property-of-the-same-object

반응형