๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’๊ณต๋ถ€/JS

[JavaScript] Arrow function vs Function

by rindev 2021. 7. 28.

์ผ๋ฐ˜ Function

  • ์ผ๋ฐ˜ ํ•จ์ˆ˜ ์•ˆ์˜ this๋Š” ์ž์‹ ์„ ๋งˆ์ง€๋ง‰์œผ๋กœ ํ’ˆ๊ณ  ์žˆ๋Š” scope๋กœ ๋ณ€ํ•œ๋‹ค (์–ด๋””์„œ "์„ ์–ธ"ํ–ˆ๋Š”์ง€ ์ค‘์š”x, ์–ด๋””์„œ "ํ˜ธ์ถœ" ํ•˜๋Š๋ƒ์— ๋”ฐ๋ผ ๋‹ค๋ฆ„)
const example = {
	name: "world",
	speak: function() {
		function getName() {
			return `${this.name}`;
		}
		return `Hello ${getName()}`;
	}
};
example.speak(); // Hello ๋˜๋Š” Hello undefined ์ถœ๋ ฅ

//์ด๋ฅผ ํ•ด๊ฒฐํ•˜๋ ค๋ฉด..
const example = {
	name: "world",
	speak: function() {
		//์—ฌ๊ธฐ๊นŒ์ง€๋Š” this์— ๊ฐ์ฒด example์ด bind๋ผ์žˆ์Œ
		const self = this; // self๋ฅผ ์„ ์–ธํ•ด์„œ ๊ฒฐํ•ฉ์‹œํ‚ด
		function getName() {
			return `${self.name}`;
		}
		return `Hello ${getName()}`;
	}
};
example.speak(); // Hello world

 

Arrow function

  • ES6 ๋ถ€ํ„ฐ ์ถ”๊ฐ€ ๋œ ํ‘œํ˜„ ํ˜•ํƒœ
  • ์ต๋ช…ํ•จ์ˆ˜ ์„ ์–ธ ๋ฐฉ์‹์œผ๋กœ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ์ฝ”๋“œ ์ž‘์„ฑ ๊ฐ€๋Šฅ
  • ์ด๋ฆ„์„ ์ง์ ‘ ์ง€์–ด์ค„ ์ˆ˜ ์—†๊ณ  ๋ณ€์ˆ˜์— ๋‹ด์•„์„œ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค
  • ์ƒ์œ„ ์ปจํ…์ŠคํŠธ๊ฐ€ ์ „์—ญ (window)
  • () => {} ๋ชจ์–‘์„ ํ•˜๊ณ  ์žˆ๋‹ค
  • self๋ฅผ ์“ฐ์ง€ ์•Š์•„๋„ ๋œ๋‹ค (์ฒ˜์Œ ๋ฐ”์ธ๋”ฉ ๋œ ์Šค์ฝ”ํ”„ ์•ˆ์—์„œ ๊ฐ€๋ฆฌํ‚ค๋Š” this๊ฐ€ ๋ณ€ํ•˜์ง€ ์•Š์Œ)
//์œ„๋ž‘ ๊ฐ™์€ ์ฝ”๋“œ์ž„
const example = {
	name: "world",
	speak: function() {
		const getName = () => {
			return `${this.name}`; //this๋ฅผ ์ •์ (lexically)์œผ๋กœ ๊ฒฐํ•ฉ์‹œํ‚ด
		}
		return `Hello ${getName()}`;
	}
};
example.speak(); // Hello world
  • ์ž์‹ ์˜ this, arguments, super, new.target์„ ๋ฐ”์ธ๋”ฉ ํ•˜์ง€ ์•Š์Œ
  • prototype ์†์„ฑ ์—†์Œ
  • addEventListener ํ•จ์ˆ˜์˜ callback ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋จ (๋‚ด๋ถ€์—์„œ this๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ)

 

์ฐธ๊ณ 

๋Œ“๊ธ€