๐Ÿฏ ์ฝ”์–ด ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ - 04 ์ฝœ๋ฐฑ ํ•จ์ˆ˜ (2)

modoleeยท2020๋…„ 9์›” 20์ผ
2
post-thumbnail

์ฝœ๋ฐฑ ํ•จ์ˆ˜๋Š” ํ•จ์ˆ˜๋‹ค

์˜ˆ์ œ - ๋ฉ”์„œ๋“œ๋ฅผ ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋กœ ์ „๋‹ฌ

const obj = {
  vals: [1, 2, 3],
  logValues: function (v, i) {
    console.log(this, v, i);
  }
};

obj.logValues(1, 2);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj, 1, 2

[4, 5, 6].forEach(obj.logValues);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// Window, 4, 0
// Window, 5, 1
// Window, 6, 2
  • ์–ด๋–ค ํ•จ์ˆ˜์˜ ์ธ์ž์— ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ „๋‹ฌํ•˜๋”๋ผ๋„ ์ด๋Š” ๊ฒฐ๊ตญ ๋ฉ”์„œ๋“œ๊ฐ€ ์•„๋‹Œ ํ•จ์ˆ˜ ์ผ ๋ฟ

์ฝœ๋ฐฑ ํ•จ์ˆ˜ ๋‚ด๋ถ€์˜ this์— ๋‹ค๋ฅธ ๊ฐ’ ๋ฐ”์ธ๋”ฉํ•˜๊ธฐ

  • ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๋ฅผ ์ฝœ๋ฐฑ ํ•จ์ˆ˜๋กœ ์ „๋‹ฌํ•˜๋ฉด ๊ฐ์ฒด์˜ ๋ฉ”์„œ๋“œ๊ฐ€ ์•„๋‹ˆ๋ผ ํ•จ์ˆ˜๋กœ ์ „๋‹ฌ๋˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ๊ฐ์ฒด๋ฅผ this๋กœ ๋ฐ”๋ผ๋ณผ ์ˆ˜ ์—†๊ฒŒ ๋จ

์˜ˆ์ œ - ์ „ํ†ต์ ์ธ ๋ฐฉ์‹

const obj1 = {
  name: 'obj1',
  func: function () {
    const self = this;
    return function () {
      console.log(self.name);
    }
  }
};

const callback = obj1.func();
setTimeout(callback, 1000);

// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj1
  • ๋ฉ”์„œ๋“œ ๋‚ด๋ถ€์—์„œ self ๋ณ€์ˆ˜์— this๋ฅผ ๋‹ด์•„์„œ ์‚ฌ์šฉ
  • ์‹ค์ œ๋กœ this๋ฅผ ์‚ฌ์šฉํ•˜์ง€๋„ ์•Š์„๋ฟ๋”๋Ÿฌ ๋ฒˆ๊ฑฐ๋กœ์›€

์˜ˆ์ œ - this๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๊ฒฝ์šฐ

const obj1 = {
  name: 'obj1',
  func: function () {
    console.log(obj1.name);
  }
};

setTimeout(obj1.func, 1000);

// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj1
  • ํ›จ์”ฌ ๊ฐ„๊ฒฐํ•˜๊ณ  ์ง๊ด€์ ์ด์ง€๋งŒ ์•„์‰ฌ์šด ๋ถ€๋ถ„๋„ ์žˆ์Œ
  • this๋ฅผ ์ด์šฉํ•ด ๋‹ค์–‘ํ•œ ์ƒํ™ฉ์— ์žฌํ™œ์šฉํ•  ์ˆ˜ ์—†๊ฒŒ ๋จ

์˜ˆ์ œ - func ํ•จ์ˆ˜ ์žฌํ™œ์šฉ

const obj1 = {
  name: 'obj1',
  func: function () {
    const self = this;
    return function () {
      console.log(self.name);
    }
  }
};
const callback = obj1.func();
setTimeout(callback, 1000);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj1

const obj2 = {
  name: 'obj2',
  func: obj1.func
};
const callback2 = obj2.func();
setTimeout(callback2, 1500);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj2

const obj3 = { name: 'obj3' };
const callback3 = obj1.func.call(obj3);
setTimeout(callback3, 2000);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj3
  • ์œ„์˜ ์˜ˆ์ œ์ฒ˜๋Ÿผ this๋ฅผ ์šฐํšŒ์ ์œผ๋กœ ํ™œ์šฉํ•œ ๊ฒฝ์šฐ์—๋Š” ์žฌ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅ
  • ํ•˜์ง€๋งŒ this๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ๊ฐ์ฒด ์ด๋ฆ„์„ ์ง์ ‘ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ์—๋Š” ์žฌ์‚ฌ์šฉ์ด ๋ถˆ๊ฐ€๋Šฅ

์˜ˆ์ œ - bind ๋ฉ”์„œ๋“œ ํ™œ์šฉ

const obj1 = {
  name: 'obj1',
  func: function () {
    console.log(this.name);
  }
};

setTimeout(obj1.func.bind(obj1), 1000);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj1

const obj2 = { name: 'obj2' };
setTimeout(obj1.func.bind(obj2), 1500);
// ์‹คํ–‰ ๊ฒฐ๊ณผ
// obj2
  • ES5์— ์ถ”๊ฐ€ ๋œ bind ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•œ๋‹ค๋ฉด ๊น”๋”ํ•˜๊ฒŒ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ
profile
๊ธฐ์ดˆ๊ฐ€ ํƒ„ํƒ„ํ•œ ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž๋ฅผ ๊ฟˆ๊ฟ‰๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€