[JS] #11 This
참조 사이트
https://www.w3schools.com/js/js_this.asp
JavaScript this
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
1. This is Me!!
this는 자신이 갖고 있는 요소를 가리킬 때 쓰이는 명령어이다.
자바스크립트에서 자신이 갖고 있는 요소에 접근할 때 코드가 불필요하게 길어질 때가 있다.
그럴 때 this를 사용하여 자신의 요소에 손쉽게 접근할 수 있다.
이제 버튼을 만든 뒤 자신의 요소에 접근하는 방법을 알아보자.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>02_this.html</title>
</head>
<body>
<h3>this</h3>
<form id="myform" name="myform">
<input type="button" name="btn1" id="btn1" value="버튼1" onclick="test1()">
<input type="button" name="btn2" id="btn2" value="버튼2" onclick="test2(this)">
<input type="button" name="btn3" id="btn3" value="버튼3" onclick="test3(this.value)">
</form>
<script>
// 참조 https://www.w3schools.com/js/js_this.asp
/*
● [this]
- 자기 자신의 요소를 가리킴
*/
</script>
</body>
</html>
버튼 1은 값을 지정해주지 않았고,
버튼 2는 this 명령어를 정해주었고,
버튼 3은 this의 value 값을 정해주었다.
2. 자신의 요소에 접근하기
1) name으로 접근하기 (비추천)
이 방식은 구식 방식이기 때문에 그렇게 추천하지는 않는다.
코드는 아래와 같으며 f 변수를 하나 선언해서 name 값을 불러오는 방식을 취한다.
function test1() {
let f=document.myform;
alert(f); // [object HTMLFormElement]
alert(f.btn1); // [object HTMLInputElement]
alert(f.btn1.value); // 버튼1
} // test1() end
2) id로 접근하기 (추천)
지금까지 흔히 써왔던 id로 접근하는 방법이다.
function test1() {
alert(document.getElementById("btn1").value); // 버튼1
} // test1() end
3. this로 접근하기
function test2(obj) {
alert(obj); // [object HTMLInputElement]
}
test2(this)는 현재 this 명령어가 지정되어있다.
그렇기 때문에 test2(this)는 그 자체의 값 모두가 넘어오게 된다.
그래서 아래처럼 this의 value 값을 바로 접근할 수도 있다.
alert(obj.value); // 버튼2
4. this의 value값으로 바로 접근하기
this의 value값으로 바로 접근하는 것도 가능하다.
function test3(val) {
alert(val); // 버튼3
} // test3() end
코드가 점점 짧아지고 간소화되는 것이 눈에 보이길 바란다.
이처럼 자신의 요소 중 필요한 요소에 손쉽게 접근할 수 있도록 도와주는 것이 바로 this 명령어이다.
이를 잘 활용하면 복잡하고 긴 코드를 단순화할 수 있고 손쉽게 프로그래밍을 할 수 있다.
5. this.form
this는 자신이 속해있는 상위 항목에 접근할 수도 있다.
this.form을 입력하면 자신의 요소가 속해있는 <form>을 불러오게 된다.
<form>
<input type="button" name="btn4" id="btn4" value="버튼4" onclick="test4(this.form)">
</form>
function test4(frm) {
alert(frm); // [object HTMLFormElement]
}
* form 주의할 점 *
- form 자체에 this를 지정해주면 위와 같이 [object HTMLFormElement] 요소에 접근한다.
- form에 this를 지정해줄 때 this.form을 지정해주면 <form>요소가 속한 상위의 <form>을 찾게 된다(사실 <form>안에 <form>이 올 수도 없다). 그래서 undefined가 출력되게 된다.
- this는 폼 컨트롤 요소에서만 사용한다. 예를 들어 <a> 태그에서는 사용이 불가하다.
↓ 테스트 해보기!!
위에서 설명했던 각각의 버튼의 접근을 읽어보며 버튼을 눌러보고 알림창을 확인해보자.