
대부분의 경우 this의 값은 함수를 호출한 방법에 의해 결정된다. 아래는 기본 바인딩 형식이며, 바인딩과 기본 바인딩에 대해 더 알아보자.
const test = {
prop: 42,
func: function () {
return this.prop;
},
};
console.log(test.func()); //42
함수를 호출하는 방법으로 this 값을 결정하는 것을 바인딩이라고 한다.
function foo() {
console.log(this); //// window
}
console.log(this === window); // true
this.b = "a";
console.log(window.b); // "a"
window.str = 'window';
function foo() {
console.log(this.str);
}
const obj = {
str: 1,
fn: foo,
}
obj.fn() // 암시적 바인딩 : 1
foo() // 기본 바인딩 : window
obj.fn()의 경우 this가 obj 객체에 바인딩되면서 str이 1이 된다.foo()의 경우 기본 바인딩으로 window의 str인 window를 출력한다.암시적 바인딩의 반대로 call apply bind 함수를 이용하여 원하는 대상에 바인딩한다.
function.prototype 객체의 메서드이다.
callfunction (thisArg, arrArr, arrArr...)
thisArg가 this로 바인딩 된다.argArr부터는 함수를 호출할 때 넘길 인자들로 구성된다.function foo(name, age) {
this.name = name;
this.age = age;
}
Person.call(foo, foo, 35);
applyfunction (thisArg, ['arrArr', 'arrArr',...])
call과 같은 기능을 하지만, 두 번째 인자들을 배열로 가져온다.
call과apply가 유용한 경우'유사배열' 객체가 있을 때
call과apply를 통해 배열의 메서드를 사용할 수 있다.
배열 메서드(shift, push, slice 등)은 원래 유사배열 객체에서 사용 불가능하지만, apply() 메서드로 arguments 객체에 마치 배열 메서드가 있는 것처럼 만들 수 있다.function foo(){ let args= Array.prototype. slice. apply(arguments, [1, 2]); console.dir(args); } foo(1,2,3);
bindcall, apply와 같이 명시적 바인딩 기능을 하지만, 바로 함수를 호출하지 않고 바인딩한 원본 함수를 얉은 복사하여 새로운 함수를 만든다.bar을 호출하면 this는 foo를 바인딩하고, say.bind(foo)는 bar 객체를 함수 say의 this로 설정한 새로운 함수를 만든다.function say(greet, ask){
console.log(greet + " " + this.name + " " + ask);
}
let foo = {name: 'Brian'};
let bar = say.bind(foo);
bar("Hi", "Good to see you"); //Hi Brian Good to see you
this는 새로 생성된 객체에 바인딩 된다.this 는 함수 자기 자신을 의미한다.function A(a) {
this.a = a;
}
let newObj = new A(2);
console.log(newObj.a); // Foo
this 바인딩의 예외 적용