함수 메소드 3가지를 알기 전에 용어 정리 먼저 하고 갑시다 !
function Car (barnd, name, color){ //Car은 class 이다.
this.brand = brand; //this는 this객체이며 여기서는 avante를 나타냄
this.name = name;
this.color = color;
}
Car.prototype.drive = function(){ // 속성, 메소드 정의
console.log(this.name + '가 운전을 합니다.');
}
let avante = new Car('hyundai','avante','black'); // avante는 인스턴스 이다.
1. apply()
주어진 this 값과 배열 로 제공되는 arguments로 함수를 호출한다.
func.apply(thisArg, [argsArray])
thisArg : func을 호출하는데 제공될 this의 값 //null인경우 전역객체로 대체
argsArray : func이 호출되어야 하는 인수를 지정하는 유사배열 객체
let a = [1,2,3,4,5];
let max = Math.max.apply(null,a);
console.log(max) //5
Math.max()함수 안에는 배열 형식이 못들어간다. apply를 사용함으로써 배열인 a 배열도 가능해짐
배열형태를 정수 나열 형태로 만들어 줄때 apply 사용한다.
2. call()
다른객체 대신 메소드를 호출하는데 사용된다.
func.call(thisObj,arg1,arg2....)
thisObj : func호출에 제공되는 this 의 값 생략가능
arg1,arg2.... : func이 호출되어야 하는 인수
let a = {
name : 'Jo'
};
let b = {
name : 'kim',
study : function () { console.log(this.name + '이 공부 하고 있습니다.'); }
}
b.study(); //kim이 공부 하고 있습니다.
b.study.call(a); //Jo이 공부 하고 있습니다.
b.study.call(a);는 b를 호출하고 있지만 매개변수에 a를 넣어 주었으므로 b가 아닌 a로 가리킨다.
function getId(el){
return el.id;
}
let list = document.querysetAll('a'); //a 태그 다 다져오기
Array.prototype.map.call(list,getId); //id가 a태그 인거 다 가져온다.
map은 배열 내장 함수 이기 때문에 배열만 매개변수로 받는다. 그러나 list는 배열이 아닌데 call을 사용해서 map을 사용할 수 있게 되었다.
3.apply VS call
function foo(a, b, c) {
console.log(a + b + c);
};
foo(1, 2, 3); // 6
foo.call(null, 1, 2, 3); // 6
foo.apply(null, [1, 2, 3]); // 6
apply는 배열 형태로 넣어주고 결과는 요소리스트로 처리 하고
call은 정수 리스트 로 들어간다.
4. bind()
bind()는 새롭게 바인딩한 함수를 만든다. 바인딩한 함수는 원본 함수 객체를 감싸는 함수이다. bind()는 call(), apply()와 같이 함수가 가리키고 있는 this를 바꾸지만 호출되지는 않는다. 따라서 변수를 할당하여 호출하는 형태로 사용된다.
func.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg: 바인딩 함수가 타겟 함수의 this에 전달하는 값
arg1, arg2, ...: func이 호출되어야 하는 인수
let a = {
name: 'Jo'
};
let b = {
name: 'Kim',
study: function() {
console.log(this.name + '이/가 공부를 하고 있습니다.');
}
};
let student = b.study.bind(a);
student(); // Jo이/가 공부를 하고 있습니다. 새로운 함수로 실행
bind() 커링
function template(name , money){
return '<h1>'+ name + '</h1><span>' + money + '</span>';
}
let template = template.bind(null,'steve');
template(100) // <h1>steve</h1><span>100</span>
'Javascript' 카테고리의 다른 글
22. 재귀함수 (0) | 2020.10.06 |
---|---|
21. 타이머 API (0) | 2020.10.01 |
20. 동기 호출 VS 비동기 호출 (0) | 2020.10.01 |
19. spread연산자 vs arguments (0) | 2020.10.01 |
18. 배열 내장메소드 총정리 (0) | 2020.10.01 |