자바스크립트 메소드 2가지 유형
함수호출의 2가지 유형
사용법:
fn.call(thisArg [,arg1[,arg2[,...]]])
fn.apply(thisArg, [argsArray])
1) call, apply의 첫번째 인자는 this, 두번째 인자는 개체를 위한 인수가 온다. 아래 예제1처럼 apply의 두번째 인자는 배열형태로 받는다.
const example = function(a, b, c) {
return a + b + c;
};
example(1, 2, 3);
example.call(null, 1, 2, 3);
examply.apply(null, [1, 2, 3]);
const obj = {
string: 'zero',
yell: function() {
alert(this.string);
};
};
const obj2 = {
string: 'what?'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what?'
2) 함수에는 arguments라는 유사배열이 있는데, 이 arguments를 조작할때 함수의 메소드들이 사용된다.
const example = function() {
console.log(Array.prototype.join.call(arguments));
};
example(1, 'string', true); // '1, string, true'
보기와 같이 아규먼트는 유사배열임에도 불구하고, call로 this를 바꿔주어, 배열의 메소드를 사용 가능하게 해준다.
사용법:
fn.bind(thisArg [,arg1[,arg2[,...]]])
const student = person2.study.bind(person1) // 변수에 할당
student() // 호출
Call:
function cat (q, w, e) {
return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);
const that = {
dog: 'bark'
}
cat.call(that, 1, 2, 3);
// expected output: undefined 1 2 3
// expected output: bark 1 2 3
Apply:
function cat (q, w, e) {
return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);
const that = {
dog: 'bark'
}
cat.apply(that, [1, 2, 3]);
// expected output: undefined 1 2 3
// expected output: bark 1 2 3
Bind:
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX());
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42