1. 메소드 안 : 메소드를 소유한 object

this : object person

1
2
3
4
5
6
7
8
var person = {
  firstName: "John",
  lastName : "Doe",
  id     : 5566,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
cs

 

2. alone(어디에도 속하지 않을 때?) : 전역 객체 (window)

1
2
3
4
<script>
var x = this;
document.getElementById("demo").innerHTML = x;
</script>
cs

 

3. 함수 안 : 전역 객체 (window)

1
2
3
4
5
6
<script>
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
  return this;
}
</script>
cs

 

4. 함수 안 (strict mode) : undefined

1
2
3
4
5
6
7
<script>
"use strict";
document.getElementById("demo").innerHTML = myFunction();
function myFunction() {
  return this;
}
</script>
cs

 

5. event 안 : event를 받는 element

this : button

1
2
<button onclick="this.style.display='none'">Click to Remove Me!</button>
 
cs

 

6. call(), apply() :  any object (그 어떤 객체도 의미 가능)

1
2
3
4
5
6
7
8
9
10
11
var person1 = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
var person2 = {
  firstName:"John",
  lastName: "Doe",
}
var x = person1.fullName.call(person2); 
document.getElementById("demo").innerHTML = x; 
cs

call(), apply() : https://www.zerocho.com/category/JavaScript/post/57433645a48729787807c3fd

 

출처 : https://www.w3schools.com/js/js_this.asp

 

 

 

반응형

+ Recent posts