방명록
- javascript - this2023년 11월 29일 09시 27분 18초에 업로드 된 글입니다.작성자: 삶은고구마
## this용법 1. Tag inline 이벤트 속성에 작성한 this는 tag객체 자신을 가리킨다. ```html <input type="checkbox" name="subject" id="subject-kor" value="국어" onchange="checkSubject(this);" /> ``` 2. 객체메소드(일반함수)의 this는 현재객체를 가리킨다. ```jsx const user = { username : '홍길동', run(){ console.log(`${this.username}이/가 달린다~`); } } ``` 3. 생성자함수(new연산자 호출)안 this는 현재객체를 가리킨다. ```jsx function Pet(name, breed, weight, age, ...colors){ this.name = name; this.breed = breed; this.weight = weight; this.age = age; this.colors = colors; } ``` 4. 일반함수 안에서 this는 window객체를 가리킨다. ```jsx const test3 = function(){ console.log(this); // window console.log(window); // window console.log(globalThis); // window }; ``` 5. class안의 this는 현재객체를 가리킨다. ```jsx class Person { constructor(name, age){ this.name = name; this.age = age; } sayHello(){ console.log(`안녕하세요, ${this.age}세 ${this.name}입니다.`); } } ``` 6. 이벤트핸들러(일반함수) 안의 this는 이벤트발생객체를 가리킨다. ```jsx document.querySelector("#foo").onclick = function(e) { console.log(this); // <div id="foo"></div> console.log(this === e.target); // true }; ``` 7. 전역에서 this는 window객체를 가리킨다. ```jsx console.log(this); // window console.log(window); // window console.log(globalThis); // window ```
'공부' 카테고리의 다른 글
aws trraform 설치,설정 (0) 2024.02.05 반복문 종류 (0) 2024.01.29 1113 -git/sourcetree사용방법 (0) 2023.11.13 1019(24일차) - sql 3일 (0) 2023.10.19 oracle sql developer 오류 (0) 2023.10.18 다음글이 없습니다.이전글이 없습니다.댓글