함수 호출과 실제 함수를 연결하는 방법
function add(x, y){
this.val = x + y;
console.log(this.val)
}
let obj = {val:0};
let boundFn = add.bind(obj, 2, 8);
boundFn() // 10
위 코드는 this값을 바인딩하는 모습이다.
this의 값에 obj를 바인딩해서 실제 함수를 연결한다.
var example = function (a, b, c) {
return a + b + c;
};
example(1, 2, 3);
example.call(null, 1, 2, 3);
example.apply(null, [1, 2, 3]);
call은 보통 함수와 똑같이 인자를 넣고, apply는 인자를 하나로 묶어 배열로 만들어 넣는 것을 알 수 있다.
배열이 아닌 유사배열은 배열이 아니기 때문에 배열의 메소드를 쑬 수 없다. 이때 call이나 apply가 효력을 발휘한다.
null인자는 this를 대체한다.
var obj = {
string: 'zero',
yell: function() {
alert(this.string);
}
};
var obj2 = {
string: 'what?'
};
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what?'
function moreThanFive(element) {
return element.length > 5;
}
let arr = ["code", "states"];
arr.filter(moreThanFive); // ["states"]
Array.prototype.filter.call(arr, moreThanFive); //["states"]
위의 코드에서 인스턴스인 arr이 먼저등장해서 뒤에 filter메소드를 적용한 방법과 this등 바인딩이 필요한 경우에 사용할 수 있는 call문법이 순서가 반대인것을 확인 할 수 있다.
이러한 방법으로 유사배열에 call과 apply를 적용하면 배열메소드를 적용할 수 있다.
bind함수가 call, apply와 다른 점은 함수를 실행하지 않는다는 점
대신 bound함수를 리턴
Currying은 여러 개의 인자를 가진 함수를 호출 할 경우, 파라미터의 수보다 적은 수의 파라미터를 인자로 받으면 누락된 파라미터를 인자로 받는 기법
function curring(num) {
return function(add) {
return num + add;
};
}
var add = curring(5);
var result = add(5);
console.log(result);
function template(name, money){
return "<h1>" + name + "</h1><span>" + money + "</span>";
}
let tmplSteve = template.bind(null, "Steve");
tmplSteve(100); //<h1>Steve</h1><span>100</span>
function Box(w, h){
this.width = w;
this.heigth = h;
this.getArea = function(){
return this.width * this.heigth;
}
this.printArea = function(){
console.log(this.getArea());
}
}
let b = new Box(100, 50);
b.printArea(); // 5000
setTimeout(b.printArea, 2000);
setTimeout(b.printArea.bind(b), 2000);