js에서 this는 조금 골치아픈 존재이다 다음과 같은 코드가 있다고 가정해보자
function sum(num){
return num+this.num1
}
해당 함수의 this.num1은 함수가 호출된 위치에 따라 값이 변결될것이다.
(함수가 메소드로 쓰일경우, 전역에서 쓰일경우 다 다르다.)
때문에 bind를 사용하여 this의 값을 고정시킬수있다 다음 코드를 살펴보자
let bindObj={num1:100}
let bindFunc=sum.bind(bindObj)
bundFunc(100)// 200
이렇게 바인드를하면 this를 넘겨줄수있다.
이렇게 사용한다면 메소드가 되어 사용되어지더라고 고정값을 넣어줄수 있다.
다음 코드를 봐보자
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
info(){
console.log(`x: ${this.x}, y: ${this.y}`);
}
}
var point = new Point(10, 20);
point.info();
point.info.bind({x: 100, y: 200})();
바인드된 값이 생성자의 x,y보다 앞서 적용된다.
all과 apply는 this를 전달할 뿐만아니라 파라미터까지 전달후 실행까지 한다.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
info(v, w) {
console.log(`x: ${this.x}, y: ${this.y}, v: ${v}, w: ${w}`);
}
}
var point = new Point(10, 20);
point.info(1, 2);
var customPoint = {x: 100, y: 200};
// 1번쨰 인자는 this, 두번쨰 인자는 파라미터
point.info.call(customPoint, 20, 30);
// apply는 배열로 파라미터를 넘긴다.
point.info.apply(customPoint, [2, 3]);