What is call, apply and bind?
2018-04-14
๊ฐ์ธ์ ์ธ ๊ณต๋ถ ๋ ธํธ๋ก, ์ค๋ฅ๊ฐ ์์ ์ ์์ต๋๋ค.
call๊ณผ apply๋ ๊ธฐ๋ฅ โ ํจ์ ํธ์ถํ๊ธฐ โ ์ ๊ฐ๊ณ ๋ฐ๋ ์ธ์๋ง ๋ค๋ฅด๋ค. ๋๋ค this ํค์๋๋ฅผ ํน์ ๊ฐ์ฒด์ ๋ฐ์ธ๋ฉ ํ๋ ๋ฉ์๋์ด๋ค.
func.apply(thisArg, argsArray)
this๋ฅผ ๋ฐ์ธ๋ฉํ ๊ฐ์ฒด, ๋๋ฒ์งธ ์ธ์๋ ํจ์๋ฅผ ํธ์ถํ ์ธ์๋ค์ ๋ฐฐ์ด์ด๋ค.var Person = function(name, age) {
this.name = name
this.age = age
}
var me = {}
Person.apply(me, ["Jane", "15"])
Person.prototype์ผ๋ก ์ฐ๊ฒฐ๋ ๊ฒ์ ์๋๊ณ ํจ์๋ฅผ ํธ์ถํ ๊ฒ์ผ ๋ฟ์ด๋ค.apply์ ๊ธฐ๋ฅ์ ๊ฐ๋ค. ๋จ, ๋๋ฒ์งธ ์ธ์๋ฅผ ๋ฐฐ์ด์ ๋ฃ์ง ์๊ณ ๊ทธ๋๋ก ๋๊ฒจ์ฃผ๋ฉด ๋๋ค.
Person.call(me, "Jane", "15")
this๋ method๊ฐ ์๋๋ผ caller์ ์ํด ๊ฒฐ์ ๋๋ค. obj.method()์ method.call(obj)๋ ๊ฐ๋ค๋ ๊ฒ์์ ์ ์ถํ ์ ์๋ค.๐ ์ธ์ ์ฌ์ฉํ ๊น?
apply์ call ๋ชจ๋ NodeList ๋ฑ๊ณผ ๊ฐ์ ์ ์ฌ ๋ฐฐ์ด ๊ฐ์ฒด์ ๋ฐฐ์ด ๋ฉ์๋๋ฅผ ์ฐ๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ค.// ์ด๋ ๊ฒ
Array.prototype.slice.apply(pseudoArray)
๐ React์์ bind()
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isToggleOn: true };
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
onClick์ ์ฝ๋ฐฑ์ผ๋ก this.handleClick์ ๋ถ๋ฌ์ฌ ๋, this๋ undefined๊ฐ ๋๋ค. ์๋ฐ์คํฌ๋ฆฝํธ์์ ํด๋์ค ๋ฉ์๋๋ ๋ํดํธ๋ก ๋ฐ์ธ๋ฉ๋์ง ์๊ธฐ ๋๋ฌธ์ด๋ค. this.handleClick = this.handleClick.bind(this); ์ด๋ ๊ฒ ๋ฉ์๋์ this(Toggle)์ ๋ฐ๋์ ๋ฐ์ธ๋ฉํด์ฃผ์ด์ผํ๋ค.๋ค๋ฅธ ๋ฐฉ๋ฒ ๐
transform-class-properties์ด ๋ํดํธ ๋ฐ์ธ๋ฉ์ ์ง์ํ๋ฉฐ, create-react-app์์๋ ์ด๋ฅผ ์ฌ์ฉํ๊ณ ์๋ค.onClick={(e) => this.handleClick(e)}์ ๊ฐ์ด arrow function ์์์ ์ธ์๋ ์๋ค.