바인드하는 함수에서 사용하는 this의 대상을 지정해주는 역할이다.
const objA = {
name: 'a',
aFunc: function() {
console.log(this.name)
},
}
const objB = {
name: 'b',
}
objA.aFunc() // (1)
// a
objA.aFunc.bind(objB) // (2)
const foo = objA.aFunc.bind(objB) // (3)
foo()
objA.aFunc 메서드에서 사용하는 this는 objB로 처리가 된다.foo()를 실행하면 a가 아닌 b가 나온다.import React from 'react'
class BindTest extends React.Component {
handleClick() {
console.log(this)
}
render() {
return (
<button type="button" onClick={this.handleClick.bind(this)}>
Goodbye bind
</button>
)
}
}
export default BindTest
버튼 클릭시
BindTest {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternals: FiberNode, …}출력
import React from 'react'
class WithoutBindTest extends React.Component {
handleClick() {
console.log(this)
}
render() {
return (
<button type="button" onClick={this.handleClick}>
Goodbye bind without this
</button>
)
}
}
export default WithoutBindTest
버튼 클릭시
undefined출력
자바스크립트의 this 는 실행시의 context
const thisTest = function() {
console.log(this.value)
}
thisTest.value = 'I am this'
thisTest() //undefined
thisTest()가 출력될 때의 context 가 전역객체이기 때문
const thisTest = function() {
console.log(this.value)
}
thisTest.value = 'I am this'
thisTest.func = function() {
console.log(this.value)
}
thisTest.func() // I am this
thisTest.func()가 출력될 때의 context 가 thisTest이기 때문
나는 4가지경우를 통해 this를 시도해보았다.
import React from "react";
class BindTest extends React.Component {
handleClick() {
console.log(this);
}
otherFunc() {
console.log(this);
this.handleClick();
}
render() {
return (
<div>
//1
<button
type="button"
onClick={() => {
this.handleClick();
}}
>
Goodbye bind
</button>
//2
<button type="button" onClick={this.handleClick}>
Goodbye bind
</button>
//3
<button
type="button"
onClick={() => {
this.otherFunc();
}}
>
Goodbye bind
</button>
//4
<button type="button" onClick={this.otherFunc}>
Goodbye bind
</button>
</div>
);
}
}
export default BindTest;
- 총 4개의 버튼이 있다.
BindTest가 this인 채로 출력된다.
실행되는 문맥이 바로 전역(window)객체라서 undefined가 출력
otherFunc()로 this가 출력되고this.handleClick();를 실행시켜 다시 this가 BindTest가 출력
otherFunc()에서 this는 undefined로 뜨고 이를 통해
접근하려는this.handleClick();에서 에러가 뜬다.
간단히 화살표함수로 쓰면 전부 같은 결과의 this를 처리한다.