JavaScript에서의 메서드 및 속성 체이닝
다음과 같은 입력 요소가 있다고 가정해 보겠습니다:
<input id="elem" value="text">
입력 요소의 텍스트를 화면에 출력해 봅시다:
let elem = document.querySelector('#elem');
console.log(elem.value); // 'text'를 출력합니다
보시다시피, 먼저 id로 요소를 가져와서
elem 변수에 저장한 다음, 이 변수에서
value 속성을 화면에 출력합니다.
사실 elem 변수를 도입하지 않고도
다음과 같이 점으로 체인을 구성할 수 있습니다:
console.log( document.querySelector('#elem').value ); // 'text'를 출력합니다
같은 방식으로 - 체인을 사용하여 - 속성을 재작성할 수도 있습니다:
document.querySelector('#elem').value = 'www';
다음 코드가 주어졌습니다:
<img id="image" src="avatar.png">
let image = document.querySelector('#image');
console.log(image.src);
위의 코드를 변수 image를 도입하는 대신
체인을 사용하도록 수정하세요.