Programming Language/Javascript

[Javascript] 02)함수표현식 & THIS

Sergemeow 2023. 4. 19. 14:59

함수 선언식

일반적인 프로그래밍 언어의 함수 정의 방식

함수 표현식

  • 함수 표현식은 함수의 이름을 생략한 익명 함수로 정의 가능
const sub = function(num1, num2){
	return num1 - num2
}
sub(7,2) // 
  • 표현식에서 함수 이름을 명시하는 것도 가능. 이 경우에는 호출에는 사용되지 못함
  • 인자 작성 시 ‘=’ 문자 뒤 기본 인자 선언 가능
const greeting = function(name = 'Anonymous'){
	return `Hi ${name}`
}

greeting() // Hi Anonymous

Spread syntax

  • 전개 구문
  • 배열의 경우는 요소, 함수의 경우는 인자로 확장 가능
// 배열과의 사용
let parts = ['shoulder', 'leg']
let body = ['head', ...parts , 'feet']
console.log(body)
// ['head', 'shoulder', 'leg', 'feet']

// 함수와의 사용
function func(a, b, ...theArgs){
	//
}

const restOpr = function(arg1, arg2, ...restArgs){
	return [arg1, arg2, restArgs]
}
restArgs(1, 2, 3, 4, 5) // [1, 2, [3, 4, 5]]
restArgs(1, 2) // [1, 2, []]

Arrow Function

화살표 함수

  • 함수를 비교적 간결하게 정의할 수 있는 문접
  • function 키워드와 중괄호를 이용한 구문을 짧게 사용하기 위해 만들어짐
  • 화살표 함수는 항상 익명 함수
    • ===함수 표현식에서만 사용 가능
  1. function 키워드 생략 가능
  2. 매개변수가 하나뿐이라면 매개변수의 ‘()’ 생략 가능
  3. 함수의 내용이 한 줄이라면 {}와 return도 생략 가능
const arrow1 = function(name){
	return `hello, ${name}`
}

// 1. function keyword deletion
const arrow2 = (name) => {return `hello, ${name}` }

// 2. if there's a single param, () deletion
const arrow3 = name => {return `hello, ${name}`}

// 3. 함수 바디가 return 을 포함한 표션식1개일 경우에 {} & return 삭제 가능
const arrow4 = name => `hello, ${name}`
  • 응용
// 1. 인자가 없다면 () or _ 로 표시 가능
let noArgs = () => 'No args'

// 2-1. object를 return 한다면 return을 명시적으로 적어줌
let returnObj = () => { return { key: 'value' }}

// 2-2. return을 적지 않으려면 괄호를 붙여야함
returnObject = () => ({key: 'value'})

this

  • 어떠한 object를 가리키는 키워드
    • 자바에서는 this와 python에서의 self는 인스턴스 자기자신을 가리킴
  • JS의 함수는 호출될 때 this를 암묵적으로 전달 받음
  • JS에서의 this는 일반적인 프로그래밍 언어에서의 this와 조금 다르게 동작
  • JS는 해당 함수 호출 방식에 따라 this에 바인딩 되는 객체가 달라짐
  • 즉, 함수를 선언할 때 this에 객체가 결정되는 것이 아니고, 함수를 호출할 때 함수가 어떻게 호출되었는지에 따라 동적으로 결정됨

this INDEX

  1. 전역 문맥에서의 this
  • 브라우저의 전역 객체인 window를 가리킴
    • 전역객체는 모든 객체의 유일한 최상위 객체를 의미
console.log(this) // window 객체가 나옴
  1. 함수 문맥에서의 this
  • 함수를 호출한 방법에 따라 달라짐

단순 호출

const myFunc = function (){
	console.log(this)
}
myFunc()
// window

Method(function in object, 객체의 메서드로서)

  • 메서드로 선언하고 호출한다면, 객체의 메서드이므로 해당 객체가 바인딩
const myObj = {
	data: 1,
	myFunc() {
		console.log(this) // myObj
		console.log(this.data) // 1
	}
}

myObj.myFunc() // myObj

Nested(Function 키워드)

  • forEach의 콜백함수에서의 this가 메서드의 객체를 가리키지 못하고 전역객체 window를 가리킴
  • 단순 호출 방식으로 사용되었기 때문
  • 이를 해결하기 위해 등장한 함수 표현식이 바로 ‘화살표 함수’
const myObj = {
	numbers : [1,2],
	myFunc() {
		console.log(this) 
		this.numbers.forEach(function(numbers)
{
			console.log(numbers) // 1, 2
			console.log(this) // window, window
		})
	}
}

myObj.myFunc()

Nested(화살표 함수)

  • 이전에 일반 function 키워드와 달리 메서드의 객체를 잘 가리킴
  • 화살표 함수에서 this는 자신을 감싼 정적 범위
  • 자동으로 한 단계 상위의 scope의 context를 바인딩
const myObj = {
	numbers : [1, 2],
	myFunc(){
		console.log(this) 
		this.numbers.forEach((number) => {
			console.log(number)
			console.log(this) // myObj
		})
	}
}

myObj.myFunc()

화살표 함수

  • 화살표 함수는 호출의 위치와 상관 없이 상위 스코프를 가리킴(lexical scope this)
  • Lexical scope
    • 함수를 어디서 호출하는지가 아니라 어디에 선언하였는지에 따라 결정
    • Static scope라고도 하며 대부분의 프로그래밍 언어에서 따르는 방식
let x = 1 //global

function first() {
	let x = 10
	second()
}

function second() {
	console.log(x)
}

first() // 1
second() // 1

// second 호출위치보다 선언위치가 하단이기 때문
  • so, 함수 내의 함수 상황에서 화살표 함수를 쓰는 것을 권장