새소식

반응형
WEB/JavaScript

[JavaScript] 자바스크립트 apply() 통한 바인딩 알아보기.

  • -
반응형

2021-07-18


Photo by Graham Pengelly on Unsplash

자바스크립트에서는 객체를 바인딩하는 몇 가지 메서드가 존재하는데, 그중에서 오늘은 apply를 알아보도록 하자.


- 예제1

 

//사람의 정보 함수
function person(name, age){
    this.hisName = name;
    this.hisAge = age;
}

const person1 =new person('king', 25);

// 학년이 추가된 학생 함수
function student(name, age, grade){
    person.apply(this, [name,age])
    this.hisGrade = grade;
}

const student1 = new student('kking', 30, 5);

console.log(person1.hisName); //king
console.log(student1.hisName); //kking
console.log(student1.hisGrade) // 5
console.log(student1) // student { hisName: 'kking', hisAge: 30, hisGrade: 5 }

 

apply는 매개 값을 두개를 받는다. 첫째는 바인딩될 객체와 두번째는 바인딩에 필요한 인수 배열이다. 예제에서는 학생함수에서의 name과 age를 기존에 존재하는 person 함수를 활용하고자 peson 함수를 student 함수에 바인딩 후 매개값 name과 age를 받아 값을 설정해 준다.

 

결과를 보면 student1에 성공적으로 데이터가 삽입되어 출력되는 것을 확인할 수 있다.


- 예제2

 

const arr1 = [1,2,3];
const arr2 = [4,5,6];

//push : 배열의 뒤에 추가한다.
//apply : arr1에 바인딩하며 인수로 arr2를 받는다.
arr1.push.apply(arr1, arr2);

console.log(arr1) // [ 1, 2, 3, 4, 5, 6 ]

 

또한 위와 같이 서로 다른 두 배열을 합치는 용도로도 사용이 가능하다.


메인 이미지 출처 : Photo by Graham Pengelly on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.