[JavaScript] bind()

๊น€์ •๋ฏผยท2022๋…„ 6์›” 8์ผ
1
post-thumbnail
post-custom-banner

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ํ•จ์ˆ˜ ํ˜ธ์ถœํ•˜๊ธฐ, bind()

bind() ํ•จ์ˆ˜๋Š” ์ƒˆ๋กญ๊ฒŒ ๋ฐ”์ธ๋”ฉํ•œ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ํ•จ์ˆ˜๋กœ, ๋ฐ”์ธ๋”ฉํ•œ ํ•จ์ˆ˜๋Š” ์›๋ณธ ํ•จ์ˆ˜ ๊ฐ์ฒด๋ฅผ ๊ฐ์‹ธ๋Š” ํ•จ์ˆ˜๋กœ์จ, ๋ฐ”์ธ๋”ฉํ•œ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ์ผ๋ฐ˜์ ์œผ๋กœ ๋ž˜ํ•‘๋œ ํ•จ์ˆ˜๊ฐ€ ํ˜ธ์ถœ ๋œ๋‹ค. (ECMAScript 2015์˜ exotic function object)

// ์‚ฌ์šฉ๋ฒ•
Function.bind(thisArg, [arg1, arg2, ...])
  • thisArg // this๊ฐ€ ๊ฐ€๋ฆฌํ‚ฌ ๊ฐ์ฒด๋ฅผ ์ง€์ •
  • [arg1, arg2 ... ] // ํ•จ์ˆ˜์˜ ์ธ์ž๋กœ ์ „๋‹ฌํ•  ๊ฐ’

์ด๋•Œ ์ฒซ ๋ฒˆ์งธ ์ธ์ž์ธ thisArg๋Š” ์„ ํƒ์˜ต์…˜์œผ๋กœ ๊ฐ’์„ ์ „๋‹ฌํ•˜์ง€ ์•Š์•„๋„ ๋˜๋ฉฐ null ๋“ฑ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ทธ ๋‹ค์Œ์€ ํ•จ์ˆ˜์— ์ „๋‹ฌ ํ•  ์ธ์ž ๊ฐ’์œผ๋กœ ๋ฐฐ์—ด ํƒ€์ž…์œผ๋กœ ์ „๋‹ฌํ•˜๊ฒŒ ๋œ๋‹ค. ์ด์ฒ˜๋Ÿผ ์ธ์ž ๊ฐ’์„ ๋ฐฐ์—ด๋กœ ์ „๋‹ฌํ•˜๋Š” ๊ฒƒ์€ apply()์™€ ๋น„์Šทํ•˜๋‹ค.

[์ƒ๊ฐํ•  ์ ] call(), apply()์™€์˜ ์ฐจ์ด์ ์€?
๊ฑฐ์˜ ๋™์ผํ•˜๊ฒŒ ํ™œ์šฉ์ด ๊ฐ€๋Šฅํ•˜์ง€๋งŒ ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•˜์ง€ ์•Š๊ณ  ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์ ์—์„œ call(), apply()์™€์˜ ์ฐจ์ด์ ์ด๋‹ค.

// ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ bind() ์˜ˆ์ œ
mySite = {
  name: 'webisfree',
  getSite: function() {
    return this.name;
  }
}

getSite ์ด๋ฆ„์˜ ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœ ํ•˜๋ฉด ์‹คํ–‰ํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๋‚˜ํƒ€๋‚ฉ๋‹ˆ๋‹ค.

mySite.getSite();

// ์ถœ๋ ฅ๊ฒฐ๊ณผ
"webisfree"

๋‹ค์Œ์œผ๋กœ getYourSite๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ  ์—ฌ๊ธฐ์— mySite.getSite ๋ฉ”์†Œ๋“œ๋ฅผ ์„ ์–ธํ•œ๋‹ค.

getYourSite = mySite.getSite;
getYourSite();

 // ์ถœ๋ ฅ๊ฒฐ๊ณผ
undefined

์‹คํ–‰ํ•ด๋ณด๋‹ˆ ๊ฒฐ๊ณผ๋Š” undefined๊ฐ€ ๋‚˜ํƒ€๋‚˜๊ฒŒ ๋œ๋‹ค. ์ฆ‰ ํ•จ์ˆ˜์˜ this์—๋Š” name์ด๋ผ๋Š” ํ”„๋กœํผํ‹ฐ๊ฐ€ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฏ€๋กœ window ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ•˜์—ฌ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

์ด์ œ bind()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ this ํ‚ค์›Œ๋“œ๊ฐ€ mySite๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ํ•œ ํ›„ ๋‹ค์‹œ ์‹คํ–‰ํ•ด๋ณธ๋‹ค.

getMySite = getYourSite.bind(mySite);
getMySite();

// ์ถœ๋ ฅ๊ฒฐ๊ณผ
'webisfree'

์ด๋ฒˆ์—๋Š” this๋ฅผ mySite๋กœ ๊ฐ€๋ฆฌํ‚ค๋„๋ก bind()๋ฅผ ์‚ฌ์šฉํ•˜์˜€๊ธฐ ๋•Œ๋ฌธ์— 'webisfree'๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ์ด์™€ ๊ฐ™์ด bind()๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด this๊ฐ€ ์–ด๋–ค ์ธ์Šคํ„ด์Šค๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ ๊ฒƒ์ธ์ง€ ์„ ํƒํ•  ์ˆ˜ ์žˆ๋‹ค.


var obj = {
    name: 'shpark'
};

function bindTest() {
    console.log(this.name);
}

bindTest(); // undefined ์ถœ๋ ฅ

var bindTest2 = bindTest.bind(obj); // bindTest ํ•จ์ˆ˜์— obj ๊ฐ์ฒด๋ฅผ bind

bindTest2(); // obj์˜ name ๊ฐ’์ธ shpark ์ด ํ‘œ์ถœ
 

์ถœ์ฒ˜ : https://webisfree.com/2021-04-24/%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%95%A8%EC%88%98%EC%97%90-bind-%EB%A9%94%EC%86%8C%EB%93%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

์ถœ์ฒ˜ : https://shplab.tistory.com/entry/Javascript-bind-%ED%95%A8%EC%88%98-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0 - ๋ฐ•์„œํฌ์—ฐ๊ตฌ์†Œ

post-custom-banner

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