1. this는 window 객체 이다
따라서 어디서든 this는 사용된다
2. this는 소속되어있는 있는 객체를 가르킨다
him.laugh를 실행한 순간, him객체의 laugh를 먼저 간다.
그 후, laugh 함수를 정의하고 있는 1번째 열의 function laugh()를 실행, 현재 실행되고 있는 객체는 him 이니까 여기서의 this는 him 객체를 나타낸다.
그냥 laugh()만 쓴경우, window.laugh()한거랑 똑같다. 근데 윈도우에 첫번쨰 열에서 함수를 정의해놨으니까, laugh()가 있고, 여기서의 return this는 윈도우 객체를 가르킨다. 즉, 자신이 소속되어있는 객체를 가르킨다.
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
// Return "John Doe":
person1.fullName.call(person2);
여기서의 this는 person2를 가르킨다. call()은 다른 객체의 함수를 일으킬 때 쓰는 함수인데, 비록 person1이라는 객체에서 fullName()이 행애진다고 하더라도 firstName와 lastName은 person2에 소속되어 있기 때문에 , 여기서의 this는 person2이다.
What is this?
In JavaScript, the this keyword refers to an object.
Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is used:
In an object method, this refers to the object. |
Alone, this refers to the global object. |
In a function, this refers to the global object. |
In a function, in strict mode, this is undefined. |
In an event, this refers to the element that received the event. |
Methods like call(), apply(), and bind() can refer this to any object. |
'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글
input안에 값넣으면 리스트 추가 (0) | 2023.02.24 |
---|---|
자바스크립트 call() (0) | 2023.02.22 |
자바스크립트 .el? (0) | 2023.02.21 |
배열 요소 삭제방법 (0) | 2023.02.21 |
Factory Functions (3) | 2023.02.19 |
댓글