본문 바로가기

코딩/Javascript

자바스크립트 bind() 사용법

반응형

bind() 함수 사용법

1
2
3
function printName() {
    console.log(this.name);
};
cs

위와 같은 printName라는 함수에 this라는 예약어는 현재 객체를 가리킨다.

 

만약 웹에서 console.log(this)를 입력하면 undefined를 출력한다

왜냐하면 thiswindow라는 객체 가리키고 (Node에선 빈 객체를 출력), window 객체엔 name이라는 프로퍼티가 없기 때문.

이 함수를 그냥 쓰면 this는 언제나 window 객체를 가리키지만, bind() 함수로 this 예약어를 원하는 객체를 가리키게 할 수 있다.

 

예를 들어, ObjectOnename을 출력, ObjectTwoname을 출력... ObjectTenname을 출력하고 싶으면 모든 객체에 이 printName() 함수를 일일이 복붙 하지 않아도 bind()로 간결하게 쓸 수 있다.

 

 

두 객체를 만든다, 둘 다 name이라는 프로퍼티를 가지고 있다.

나는 두 객체에서 name 프로퍼티를 출력하는 함수를 만들고 싶다.

1
2
3
4
5
6
7
const teacher = {
    name'Smith',
};
 
const student = {
    name'John',
};
cs

 

 

두 객체에 printName이라는 프로퍼티를 만들고 미리 코드 한 printName() 함수를 삽입시키면 되지만

코드의 반복성이 있고 완벽히 동적이지는 못하다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function printName() {
    console.log(this.name);
};
 
const teacher = {
    name'Smith',
    printName: printName,
};
 
const student = {
    name'John',
    printName: printName,
};
 
console.log(teacher.printName());
console.log(student.printName());
cs

 

게다가 결과는 두 객체의 name 프로퍼티를 출력하지만 printName() 함수 출력 후 undefined도 출력돼 완벽하지 않다.

 

 

 

이제 bind()를 이용해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function printName() {
    console.log(this.name);
};
 
const teacher = {
    name'Smith',
};
 
const student = {
    name'John',
};
 
const printTeacherName = printName.bind(teacher);
const printStudentName = printName.bind(student);
 
printTeacherName();
printStudentName();
cs

 

13번 줄, printName.bind(teacher)의 반환 값을 printTeacherName이라는 변수에 할당한다.

이때 printTeacherName의 함수는 마치

1
2
3
function printTeacherName() {
    console.log(teacher.name);
}
cs

위에 코드와 동일하다

 

그래서 실행을 시키면

 

성공

 

printName.bind(teacher)의 경우 printName() 속 this 값은 teacher이고.

printName.bind(student)의 경우 printName() 속 this 값은 student이다.

 

참고로 printTeacherName 변수 없이 바로 printName.bind() 함수를 사용하고 싶으면

const printTeacherName = printName.bind(teacher); 대신

printName.bind(teacher)();printTeacherName이라는 변수 없이 바로 teacher name를 출력할 수 있다

 

 

 

반응형