728x90
반응형
this 정의
this는 '자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수'
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메소드를 참조할 수 있다.
<모던 자바스크립트> 이웅모 저
this는 일반적으로 메소드를 호출한 객체가 저장되어 있는 속성.
'또는' 이라는 표현으로 this가 고정된 값에 바인딩되어 사용되지 않는다는 것을 의미합니다.
this는 '함수가 호출되는 방식'에 따라 '동적'으로 결정된다.
this호출경우
1. 일반함수에서 this => window
2. 메소드에서 this => 호출한 객체
3. 생성자 함수 호출 this => 생성할 객체
4. Call, Apply, Bind 메소드 사용시 => 메서드 첫번째 인수로 전달하는 객체에 바인딩
1.일반함수에서 this => window
console.log(this === window);
data = 30;
console.log(window.data);
console.log(this.data);
function test() {
return this;
}
test() === window;
2.메소드에서 this => 호출한 객체
var name = {
firstName: "June",
lastName: "Shin",
introduce() {
console.log("my name is " + this.firstName)
console.log(this === window) // false
}
}
name.introduce(); // my name is June
3. 생성자 함수로 호출시 this =>생성할 객체에 바인딩
function person() {
this.firstName = "June",
this.lastName = "Shin",
this.introduce = function() {
console.log("my name is " + this.firstName) // my name is June
}
}
let person1 = new person();
console.log(person1) // { person 객체}
4. Call, Apply, Bind 메소드 사용시 => 첫번째 인수로 전달하는 객체
참고 :
728x90
반응형
'프로그래밍 > 웹' 카테고리의 다른 글
[한글입숨] 무의미한 텍스트 출력(더미텍스트 생성) (0) | 2022.06.27 |
---|---|
[자바스크립트] 화살표함수 (0) | 2021.07.29 |
[자바스크립트] call, apply, bind (0) | 2021.07.29 |
브라우저 저장소 (local Storage, session storage, cookie) (0) | 2021.07.27 |