본문 바로가기
프로그래밍/웹

[자바스크립트] this객체

by 공대부부 남편 2021. 7. 29.
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 메소드 사용시 => 첫번째 인수로 전달하는 객체

 

 

 

 

 

참고 :

https://beomy.tistory.com/6

https://oneroomtable.tistory.com/entry/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-this%EB%9E%80-%EB%8C%80%EC%B2%B4-%EB%AC%B4%EC%97%87%EC%9D%BC%EA%B9%8C

728x90
반응형