This์๐ bind๐๏ธ ์ฐธ ์ฝ์ฃ ์!
-WHAT ISโ
ํด๋ก์
)์ด ์๊ณ this
๋ค.
- ๋๋ถ๋ถ์ ๊ฒฝ์ฐ 1>
this์ ๊ฐ(๋ฐ์ธ๋ฉ)
์ ํจ์๋ฅผ ํธ์ถํ๋ ๋ฐฉ๋ฒ์ ์ํด ๊ฒฐ์ ๋์ง๋ง- ํจ์์
this ๊ฐ
์ด ํจ์๊ฐ ์ด๋ป๊ฒ ํธ์ถ๋์๋์ง์ ๋ฌด๊ดํ๊ฒ 2>this
๋ฅผ ์ค์ ํ ์ ์๋bind ๋ฉ์๋
๋ ์(?)๋ ์๋ค.
-HOW TO USEโโ
this
!<script> const someone = { // ๊ฐ์ฒด ์์ ํ๋กํผํฐ์ ๋ฉ์๋ ์กด์ฌ name: 'jamie', whoAmI : function(){ console.log(this) } }; // Q1. whoAmI ํจ์๋ฅผ ํธ์ถํ ๋ ์? someone.whoAmI(); // A1. someone, {name: "jamie", whoAmI: f} </script>
- A. 1๋ฒ> whoAmI() ํธ์ถํ ๋ ์,
this
๋ ๋ฐ๋ก ๋ฉ์๋๋ฅผ ํธ์ถํsomeone ๊ฐ์ฒด
๋ก
1>๋ฉ์๋ ํธ์ถ ๋ฐฉ์
์ผ๋ก ํธ์ถ ํ์๋ค.
=> ์ด์ฒ๋ผthis
๋ ํธ์ถํ๋ ๋ฐฉ์, ์ฆ ํธ์ถ์ ๋๊ฐ ํ๋๋์ ๋ฐ๋ผ ๊ฒฐ์ ๋๋ค.<script> const someone = { // ๊ฐ์ฒด ์์ ํ๋กํผํฐ์ ๋ฉ์๋ ์กด์ฌ name: 'jamie', whoAmI : function(){ console.log(this) } }; // Q2. myWhoAmI ํจ์๋ฅผ ํธ์ถํ ๋ ์? const myWhoAmI = someone.whoAmI; myWhoAmI(); // A2. window </script>
- A. 2๋ฒ> myWhoAmI()ํธ์ถํ ๋ ์,
this
๋ ๋ฐ๋ก global ๊ฐ์ฒด,window
๋ก ๊ฐ์ฒด์ ๋ฉ์๋๋ฅผ ๋ณ์์ ํ ๋นํ์ฌ 2>์ผ๋ฐ ํจ์๋ก์ ํธ์ถ ๋ฐฉ์
์ผ๋ก ํธ์ถํ์๋ค.<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>page title</title> </head> <body> <h1>JAMIE</h1> <Button id="btn"><h2>Hello</h2></Button> <script> const someone = { // ๊ฐ์ฒด ์์ ํ๋กํผํฐ์ ๋ฉ์๋ ์กด์ฌ name: 'jamie', whoAmI : function(){ console.log(this) } }; const btn = document.getElementById('btn'); // Q3. someone.whoAmI๋ฅผ ํธ์ถํ ๋ ์? btn.addEventListener('click', someone.whoAmI); // <Button id="btn"><h2>Hello</h2></Button> </script> </body> </html>
- A. 3๋ฒ> HTML ๋ฌธ์์ id 'btn'์ Button ํ๊ทธ๋ก ๋ฒํผ์ ๋ง๋ค์ด ๋ฒํผ์ ํด๋ฆญ ์ someone.whoAmI๋ฅผ ํธ์ถํ ๋ ์,
this
๋ ๋ฐ๋กHTMLButtonElement(btn)
์ด๋ค.- ์ด๋
btn
์someone์ whoAmI๊ฐ ์๋whoAmI ํจ์๋ง๋.๊ธด.๊ฒ
๊ณผ ๋์ผํด
์ฆ,btn.addEventListener('click', myWhoAmI)
,myWhoAmI ํธ์ถํ ๊ฒ ์๋๋.๊ธด.๊ฒ
๊ณผ ๋์ผํ๋ค.
=> ํจ์๋ฅผ ํธ์ถํ ๋ ์์btn
์ผ๋ก ํด๋ฆญ์ ๋๊ธด ํจ์๋ฅผ ํธ์ถํ๋ผ ๋ช ๋ น์ ๋ด๋ฆฐ ๋(?)์ด๋ค.
bind
!
- ๊ทธ๋ฌ๋ ํธ์ถํ๋ ๊ฒ๊ณผ ๋ฌด๊ดํ๊ฒ this๋ฅผ ๊ณ ์ ์ํค๋ ๋ฉ์๋ ๋ ์์ด
bind
์ด๋ค.<html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>page title</title> </head> <body> <script> const someone = { name: 'jamie', whoAmI : function(){ console.log(this) } }; // Q4. bindWhoAmI ํธ์ถํ ๋ ์์? const bindWhoAmI = myWhoAmI.bind(someone) bindWhoAmI(); // { name: "jamie", whoAmI: f} btn.addEventListener('click',bindWhoAmI); // { name: "jamie", whoAmI: f} </script> </body> </html> </head>
- A. bindWhoAmI๋ฅผ ํธ์ถํ ๋ ์์
bind ๋ฉ์๋
๊ฐ ๋๊ธด ์ธ์ ๋ ์(?)์ผ๋ก ๋ฐ๋ก **someone ๊ฐ์ฒด
๋ค.bind ๋ฉ์๋
๋ ์์ ํธ์ถํ ๋ ์๊ณผ ๋ฌด๊ดํ๊ฒ ๋ฌด์กฐ๊ฑด ์ธ์๋ก ๋๊ธด ๋ ์์this
๋ก ๊ณ ์ ์์ผ๋ฒ๋ฆฐ๋ค.
=> ๋์ฒด ๋.๊ฐ.ํธ.์ถํ์ด?!
- ์๋ฐ์คํฌ๋ฆฝ๋ ์ ์ธํ ๋ ๊ฒฐ์ ๋๋ ๊ฒ๊ณผ ํธ์ถ ํ ๋ ๊ฒฐ์ ํ๋ ๊ฒ์ด์๋๋ฐ ์ด ํธ์ถํ ๋ ๊ฒฐ์ ๋๋ ๋ ์์ด ๋ฐ๋ก
this
๋ก ํธ์ถํ ๋,ํธ์ถํ ๊ฐ์ฒด
๋ฅผ ์๋ฏธํ๋ค.- ์ด
this
๋ฅผ ์์ธ์ ์ผ๋ก ๋ฌถ์ด์ค ๊ณ ์ ํ ์ ์๋ ๋ ์์ด ๋ฐ๋กbind
์ด๋ค.
- ์ฝ๋์ข ๋ - https://www.youtube.com/watch?v=PAr92molMHU&t=310s