Meiren

[Javascript] 기본 - 객체 (method / this) 본문

GTM(구글태그매니저)

[Javascript] 기본 - 객체 (method / this)

meiren 2023. 4. 10. 17:14

1. object

const superman = {
	name : 'clark',
    	age : 33,
    	fly : function(){
    		console.log('날아갑니다.')
       }
}

superman.fly()        // 날아갑니다.

 

 

2. method

객체 프로퍼티로 할당된 함수

fly : function(){} -> fly(){}

const superman = {
	fly(){
    	console.log('날아갑니다.')
}

 

 

3. this

3-1. 객체 안에서 this

const user = {
	name : 'Mike',
		sayHello : function(){
		console.log(`Hello, I'm ${this.name}`);
	}
}


user.sayHello();         // Hello, I'm Mike

 

3-2. 함수 내에서 this

this 는 실행하는 시점(runtime)에 결정됩니다.

this는 . 앞에 있는 객체(boy, girl)

sayHello : function(){
	console.log(`Hello, I'm ${this.name}`);
}


let boy = {
	name = 'Mike',
    sayHello,
}

let girl = {
	name = 'Jane',
    sayHello,
}


boy.sayHello();        // Hello, I'm Mike
girl.sayHello();       // Hello, I'm Jane

 

 

boy.name으로 콘솔로그 찍힐 때, boy = null해버리면

man 사용해도 결국 boy.name 이기에 null이 나온다.

let boy = {~~~showName : function() {consol.log(boy.name)} }
let man = boy
boy = null


man.showName()     // error

 

따라서 만일 boy.name 이 아니라 -> this.name 으로하면 -> man -> man.name이 되기에 

boy = null이어도 man은 무관하다

let boy = {~~~showName : function() {consol.log(this.name)} }
let man = boy
boy = null


man.showName()     // error

 

 

 

3-3. 화살표 함수와 this

화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않음

화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져옴

따라서 메서드에서 this 쓸 때는 화살표 함수를 신중이 사용

let boy = {
	name : "Mike",
    sayThis : {} => {
    	console.log(this);   // 화살표함수의 this는 boy가 아닌 전역객체(윈도우)
	}
}
boy.sayThis();