ํ™”์‚ดํ‘œํ•จ์ˆ˜

๊ธฐ์กด์˜ function ํ‘œํ˜„๋ฐฉ์‹๋ณด๋‹ค ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ•จ์ˆ˜๋ฅผ ํ‘œํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค. ํ™”์‚ดํ‘œํ•จ์ˆ˜๋Š” ํ•ญ์ƒ ์ต๋ช…์ด๋ฉฐ, ์ž์‹ ์˜ this, arguments, super, new.target์„ ๋ฐ”์ธ๋”ฉํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋”ฐ๋ผ์„œ ์ƒ์„ฑ์ž๋กœ๋Š” ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋‹ค.

  • ํ™”์‚ดํ‘œํ•จ์ˆ˜ ๋„์ž… ์˜ํ–ฅ : ์งง์€ ํ•จ์ˆ˜, ์ƒ์œ„ ์Šค์ฝ”ํ”„ this

์งง์€ ํ•จ์ˆ˜

var materials = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
 
materials.map(function (material) {
  return material.length;
}); // [8, 6, 7, 9]
 
materials.map((material) => {
  return material.length;
}); // [8, 6, 7, 9]
 
materials.map(({ length }) => length); // [8, 6, 7, 9]

์ƒ์œ„์Šค์ฝ”ํ”„ this

function Person() {
  this.age = 0;
 
  setInterval(() => {
    this.age++; // |this|๋Š” person ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐ
  }, 1000);
}
 
var p = new Person();

์ผ๋ฐ˜ ํ•จ์ˆ˜์—์„œ this๋Š” ์ „์—ญ๊ฐ์ฒด๋ฅผ this๋กœ ์ •์˜ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ํ™”์‚ดํ‘œ ํ•จ์ˆ˜ this๋Š” ์ƒ์œ„ ์Šค์ฝ”ํ”„์˜ this์™€ ๋™์ผํ•œ ๊ฐ’์„ ๊ฐ–๋Š”๋‹ค. ๋”ฐ๋ผ์„œ ์œ„ ์˜ˆ์ œ์—์„œ setInterval๋กœ ์ „๋‹ฌ๋œ this๋Š” Person์˜ this๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋ฉฐ, Person ๊ฐ์ฒด์˜ age์— ์ ‘๊ทผํ•œ๋‹ค.


ํ™”์‚ดํ‘œํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋˜๋Š” ์ˆœ๊ฐ„

๋ฉ”์†Œ๋“œ

const cat = {
  name: 'meow';
  callName: () => console.log(this.name);
}
 
cat.callName();	// undefined

์ด ๊ฒฝ์šฐ ํ™”์‚ดํ‘œํ•จ์ˆ˜์˜ ์ƒ์œ„ ์Šค์ฝ”ํ”„๋Š” ์ „์—ญ this๊ฐ€ ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฉ”์†Œ๋“œ๋กœ ํ™”์‚ดํ‘œํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•ˆ๋œ๋‹ค.

๋ฉ”์†Œ๋“œ์˜ ๊ฒฝ์šฐ, ํ˜ธ์ถœํ•œ ๊ฐ์ฒด์˜ this๋กœ ๋ฐ”์ธ๋”ฉ๋˜๋‹ˆ ์ผ๋ฐ˜ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์ž

์ƒ์„ฑ์ž

const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructor

ํ™”์‚ดํ‘œํ•จ์ˆ˜์—๋Š” prototype์ด ์—†๊ธฐ์— ์ƒ์„ฑ์ž๋กœ ์‚ฌ์šฉํ•  ์ˆ˜๋Š” ์—†๋‹ค.

addEventListener()์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜

const button = document.getElementById("myButton");
 
button.addEventListener("click", () => {
  console.log(this); // Window
  this.innerHTML = "clicked";
});
 
button.addEventListener("click", function () {
  console.log(this); // button ์—˜๋ฆฌ๋จผํŠธ
  this.innerHTML = "clicked";
});

addEventListener์˜ ์ฝœ๋ฐฑํ•จ์ˆ˜์—์„œ this ๋Š” ์ด๋ฒคํŠธ๋ฆฌ์Šค๋„ˆ๊ฐ€ ํ˜ธ์ถœ๋œ ์—˜๋ฆฌ๋จผํŠธ๋กœ ๋ฐ”์ธ๋”ฉ๋œ๋‹ค.

ํ•˜์ง€๋งŒ ํ™”์‚ดํ‘œํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์ƒ์œ„์Šค์ฝ”ํ”„๋กœ ๋ฐ”์ธ๋”ฉ๋˜๋ฏ€๋กœ, ์ „์—ญ this๊ฐ€ ์‚ฌ์šฉ๋˜๊ฒŒ ๋œ๋‹ค.



์ถœ์ฒ˜

https://github.com/JaeYeopHan/Interview_Question_for_Beginner/tree/master/JavaScript#promise

https://velog.io/@padoling/JavaScript-%ED%99%94%EC%82%B4%ED%91%9C-%ED%95%A8%EC%88%98%EC%99%80-this-%EB%B0%94%EC%9D%B8%EB%94%A9