재우니의 블로그

 

 

 

javascript 의 .call(), .apply(), .bind() 함수 사용법

 

medium.com/@akhilgoyal_/understanding-call-bind-apply-methods-in-javascript-in-simplest-way-7f466353736c

 

Understanding call(), bind() & apply() methods in JavaScript in simplest way!

Hello everyone! In this article, we shall try to understand the functionalities of JavaScript methods call(), bind() and apply(). In order…

medium.com

 

 

employeeOne 에는 salaryHikoNo() , salaryHike(hike) 함수가 존재하며, employeeTwo 에는 존재하지 않습니다.

 

만약에 employeeTwo 에서 employeeOne 에 존재하는 2개의 함수를 사용하고자 할 경우에는 .call(), .apply(), .bind() 를 통해 접근이 가능합니다.

 

call 함수

 

call 함수를 통해 employeeOne 에 salaryHike 를 사용하고 싶으며, 데이터는  employeeTwo 를 기준으로 한다고 할 경우

 

employeeOne.salaryHike.call(employeeTwo, 파라미터값);

 

apply 함수

 

apply 함수를 통해 employeeOne 에 salaryHike 를 사용하고 싶으며, 데이터는  employeeTwo 를 기준으로 한다고 할 경우, 파라미터 값은 배열형태 [ ] 로 전송해야 합니다.

 

employeeOne.salaryHike.call(employeeTwo, [50000]);

 

bind 함수

 

bind 함수를 통해 employeeOne 에 salaryHike 를 사용하고 싶으며, 데이터는  employeeTwo 를 기준으로 한다고 할 경우, bind 는 반환값을 값이 아닌 함수형태 이므로 변수에 받아서 함수를 실행한 다음 값을 얻을 수 있습니다.

 

var hikeEmployeeTwo = employeeOne.salaryHike.bind(employeeTwo, 500);
hikeEmployeeTwo();

 

전체적인 코드

 

전체적인 코드는 아래와 같습니다.

 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let employeeOne = {
            fullName : 'John',
            age : 24,
            salary : 400000,
            salaryHikeNo(){
                this.salary += 1000
            },
            salaryHike(hike){
                this.salary += hike
            }
        }

        let employeeTwo = {
            fullName : 'korea',
            age : 25,
            salary : 500000
        }

        //#### call() 함수 사용법
        console.log(employeeTwo.salary);
        employeeOne.salaryHikeNo.call(employeeTwo);
        console.log(employeeTwo.salary);

        //#### call() 파라미터 함수 사용법
        console.log(employeeOne.salary);
        employeeOne.salaryHike.call(employeeTwo, 500);
        console.log(employeeTwo.salary);

        //#### apply() 파라미터 함수 사용법
        console.log(employeeTwo.salary);
        //.apply() 는 배열 형태로 파라미터 가능함.
        employeeOne.salaryHike.apply(employeeTwo, [500]);
        console.log(employeeTwo.salary);


        //#### bind() 파라미터 함수 사용법
        console.log(employeeTwo.salary);
        //.bind () 메서드를 사용할 때 함수를 반환하기 때문
        var hikeEmployeeTwo = employeeOne.salaryHike.bind(employeeTwo, 500);

        //반환받은 함수를 실행
        hikeEmployeeTwo();
        console.log(employeeTwo.salary);

        
    </script>

</body>

</html>