해당 내용은 '코어 자바스크립트' 서적을 참고하여 작성되었으며, 초보 개발자에게 유익한 책을 지필해주신 지은이 정재남 님께 감사의 말씀을 드립니다.
call
, apply
메서드를 활용하여 함수를 실행하면 this
값을 지정할 수 있다.function test() {
console.log(this);
}
test(); // 전역객체 출력
test.call({ x: 1 });
test.apply({ x: 1 });
// 둘다 {x:1} 출력
function test(x, y) {
console.log(x);
console.log(y);
}
// 두 메서드 모두 첫번째 인자로 this를 지정하고, 두번째 인자부터는 해당 함수의 매개변수(이자)를 대입한다
test.call(null, 1, 2); // call 메서드는 있는 그대로 나열한다
test.apply(null, [1, 2]); // apply 메서드는 배열로 감싸준다
// 유사배열객체
var obj = {
0: 'a',
1: 'b',
2: 'c',
length: 3,
};
// 요소 추가
Array.prototype.push.call(obj, 'd');
console.log(obj);
// {'0': 'a', '1': 'b', '2': 'c', '3': 'd', length: 4 }
// 배열로 전환
var arr = Array.prototype.slice.call(obj);
console.log(arr);
// [ 'a', 'b', 'c', 'd' ]
하지만 이런식으로 변환해주는 것은 call/apply 의 원래 의도와는 맞지 않으며, 코드를 해석하기도 쉽지 않아 ES6 에는 Array.from 이라는 메서드가 새로 나왔다.
var arr = Array.from(obj); console.log(arr); // [ 'a', 'b', 'c', 'd' ]
call
, apply
를 통해 this
값을 전달하여 생성자의 재사용성을 확보할 수 있다.function Person(name, gender) {
this.name = name;
this.gender = gender;
}
function Student(name, gender, school) {
Person.call(this, name, gender); // Student 의 this 값을 Person 으로 전달
this.school = school;
}
var anw = new Student('son', 'male', 'wecode');
console.log(anw); // Student { name: 'son', gender: 'male', school: 'wecode' }
// 이런식으로 this 와 call 사용해서 반복적으로 사용할 수 있다.
apply
구문을 이해할 수 있다var arr = [7, 3, 5, 9];
var max = Math.max.apply(null, arr);
// max 함수의 매개변수로 배열의 요소를 넣어야할 때 apply 활용하여 배열을 그대로 배치할 수 있다.
// 첫번째 인자로 null 넣었지만, 사실 이는 this 정보이기 때문에 출력값과는 아무 상관이 없다.
console.log(max); // 9
스프레드 연산자 활용
배열의 요소를 비교할 때 또다른 방법으로 스프레드 연산자를 사용할 수 있다var arr = [7, 3, 5, 9]; var max = Math.max(...arr); console.log(max); // 이런식으로 요소만을 복사하는 연산자를 활용하여 간편하게 작성할 수도 있다