JavaScript this 키워드는 그것이 속한 객체를 참조합니다. 단독으로 또는 함수 내부에 있는 경우 전역 개체를 참조할 수 있습니다. 메소드 내부의 경우 소유자 객체를 참조하고 이벤트 리스너에서 이벤트를 수신한 HTML 요소를 참조합니다.
예시
다음은 JavaScript this Identifier의 코드입니다 -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JavaScript this Identifier</h1>
<div class="sample"></div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to see which object 'this' refers to in multiple
context
</h3>
<script>
let thisRef = this;
let sampleEle = document.querySelector(".sample");
function test() {
return this;
}
let testObj = {
a: 22,
check() {
return this;
},
};
document.querySelector(".Btn").addEventListener(
"click",
() => {
sampleEle.innerHTML = "This inside normal function = " + test() + "<br>";
sampleEle.innerHTML += "This inside a method = " + testObj.check() + "<br>";
sampleEle.innerHTML += "This without any scope = " + thisRef + "<br>";
},
false
);
</script>
</body>
</html> 출력
위의 코드는 다음과 같은 출력을 생성합니다 -

"여기를 클릭하십시오" 버튼을 클릭하면 -
