-
[Javascript] call, apply, bind?Front-end/Javascript 2020. 6. 16. 21:32반응형
들어가기 전에, this
call, applly, bind를 알기 전에 꼭 알아야할 개념 this
JS에서는 몰라서는 안 될 존재이다. 정.말.로
우리는 망각의 동물이기에 까먹었거나, 처음 들어보는 개념이라는 아래 이 링크를 참고할 것을 권장한다.
요약해보자면,
Javascript에서 this는 객체가 속해 있는 곳을 가르킨다. Scope를 공부하시면 더 잘 이해할 수 있다.
case1: 아래에서처럼 Object의 method에서의 person 객체를 가르킨다.
var person = { firstName: "Daniel", lastName : "Park", id : 1, fullName : function() { return this.firstName + " " + this.lastName; } };
case2: 아래와 같은 this는 전역 객체(global object) widnow를 가르킨다.
var x = this;
case3: 아래의 경우의 this 또한, 전역 객체(global object) widnow를 가르킨다.
function myFunction() { return this; }
case1, 2, 3을 이해할 수 있을 정도면 call, apply, bind를 이해할 수 있다.
그렇지 않다면 이 링크를 꼭 다녀오자.
call, apply
call()과 apply()는 비슷한 역할을 합니다.
우선 call()은 첫 번째로 들어가는 parameter이 this로 대체하게 됩니다.
(1)에서 볼 수 있듯이, person1을 call 인자로 넣으면, "Daniel Park"을 리턴합니다.
하지만, person 객체에서는 firstName, lastName을 선언 & 초기화 한 적이 없기 때문에 (3)에서처럼 "undefined undefined"를 리턴합니다.
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName:"Daniel", lastName: "Park" } var person2 = { firstName:"Minion", lastName: "Park" } // (1) Will return "Daniel Park" person.fullName.call(person1); // (2) Will return "Minion Park" person.fullName.call(person2); // (3) Will return "undefined undefined" person.fullName();
call()과 apply()의 차이는 사실 별거 없다..
(1)에서처럼 this와 parameters를 단순히 나열한다면 call()
(2)에서처럼 this와 배열 형태의 parameters를 사용한다면 apply()를 사용한다.
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"Daniel", lastName: "Park" } // (1) person.fullName.call(person1, "Seoul", "Korea"); // (2) person.fullName.apply(person1, ["Seoul", "Korea"]);
bind
bind() 메소드가 호출되면 새로운 함수를 만들게 됩니다.
bind의 매개변수는 this를 대체할 객체로 세팅하게 되고, 이 객체가 바인드 되어 새로운 함수가 됩니다.
(1)에서 볼 수 있듯이, 아직 변수를 초기화&선언하지 않았기 때문에, person.fullName()은 "undefined undefined"를 리턴합니다.
(2)에서는 person.fullName에 person1을 this로 바인딩 시킨 함수를 만듦으로써, test를 실행시켰을 때, "Daniel Park"을 리턴하게 됩니다.
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName:"Daniel", lastName: "Park" } // (1) Will return "undefined undefined" person.fullName(); // (2) Will return "Daniel Park" var test = person.fullName.bind(person1) test()
참고
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
MDN: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
w3school: www.w3schools.com/js/js_function_apply.asp
zerocho: https://www.zerocho.com/category/JavaScript/post/57433645a48729787807c3fd반응형'Front-end > Javascript' 카테고리의 다른 글
[Javascript] 쓰로틀링, 디바운싱(throttling, debouncing)? (0) 2020.07.26 [Javascript] 프로토타입(Prototype)? (0) 2020.07.19 [Javascript] async & await? (0) 2020.06.14 [Javascript] sort() 함수의 함정 (0) 2020.05.17 [Javascript] es6 함수들 도중 break? (0) 2020.05.05