JS/Javascript

[Javascript] this

ui-o 2024. 6. 7. 15:17
반응형
  • this의 값은 함수가 호출되는 방식에 따라 다름

객체 내 this

  • 객체 내 this를 호출하는 경우 해당 객체를 가리킴
// 스코프 내 this 호출
const temp = {
	inner : function(){
		console.log(this)
	}
}
temp.inner() // 해당 객첼ㄹ 가리킴

전역 범위에서의 this

  • 전역 범위에서 this 호출 시 Window 객체를 가리킴
  • 'use strict' 를 활용하여 Window 객체 참조 방지 가능
  • strict 모드에서 window 객체 대신 undefined로 값을 설정하는 규칙이 적용되어 undefined가 되는 경우 bind() 함수를 활용하여 this 값을 수동으로 설정 할 수 있음

// 전역 범위에서 this 호출
function temp02(){
	console.log(this)
}
temp02() // Window {...}
// bind를 활용한 this 값 수동 설정
const tempObj = {
	color:'red',
	funcThis : function(){
		console.log(this.color)
	}
}

const tempFunc = tempObj.funcThis
console.log(tempFunc()) // undefined

const tempFunc02 = tempFunc.bind(tempObj)
console.log(tempFunc02()) // red


call() 에서의 this

  • call()에서  this를 활용한 함수 호출 시 인수의 목록을 받음

// Call 활용 
function Car(m, c){
	this.carM = m
	this.carC = c
}

function myCar(m, c) {
	Car.call(this, m, c) // call()에 객체를 전달하여 this.carM이 myCar의 인수로 전달한 m으로 설정되도록 함
	this.age = 5
}

const newCar = new myCar('audi', 'blue')
console.log(newCar.carM) // audi
console.log(newCar.carC) // blue
console.log(newCar.age)	// 5

apply() 에서의 this

  • apply()에서 this를 활용한 함수 호출 시 하나의 인수 배열을 받음
  • 함수에 필요한 인수의 수를 모르거나 알 필요가 없는 경우 주로 사용
  • 배열을 전달할 수 있으며 배열에 포함돈 원수의 수에 관계없이 함수 내부로 전달 가능

// apply 활용
function Car(m, c) {
	this.carM = m;
	this.carC = c;
}

function myCar(m, c) {
	Car.apply(this, [m, c]); // apply 활용하여 인수 목록이 담긴 배열을 받음
	this.age = 5;
}

const newCar = new myCar("audi", "blue");
console.log(newCar.carM); // audi
console.log(newCar.carC); // blue
console.log(newCar.age); // 5

// 전달하는 인수의 수에 관계없이 apply()가 호출될 때 개별적ㅇ로 각 인수가 적용 됨
const tempFunc = function(item, method, arg) {
	method.apply(args)
}

tempFunc(item, method, ['arg1', 'arg2'])
tempFunc(item, method, ['arg1', 'arg2', 'arg3'])

반응형