자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수
strict mode 해제 시 전역 객체, 적용 시 undefined
가 바인딩 됨
function foo() {
console.log(this); // window
function bar() {
console.log(this); // window
}
bar();
}
foo();
'use strict';
function foo() {
console.log(this); // undefined
function bar() {
console.log(this); // undefined
}
bar();
}
foo();
const obj = {
foo() {
console.log(this); // {foo: ƒ}
function bar() {
console.log(this); // window
}
bar();
},
};
obj.foo();
const obj = {
foo() {
console.log(this); // {foo: ƒ}
setTimeout(function () {
console.log(this); // window
}, 1000);
},
};
obj.foo();
this
를 지역 변수에 할당const obj = {
foo() {
const that = this;
setTimeout(function () {
console.log(that); // {foo: ƒ}
}, 1000);
},
};
obj.foo();
bind
적용const obj = {
foo() {
console.log(this); // {foo: ƒ}
const bar = function () {
console.log(this); // {foo: ƒ}
}.bind(this);
bar();
},
};
obj.foo();
const obj = {
foo() {
console.log(this); // {foo: ƒ}
setTimeout(() => console.log(this), 1000); // {foo: ƒ}
},
};
obj.foo();
메소드를 호출한 객체가 바인딩 됨
const obj = {
gender: 'M',
foo() {
console.log(this);
},
};
const obj2 = {
gender: 'F',
};
obj2.foo = obj.foo;
obj2.foo(); // {gender: 'F', foo: ƒ}
생성자 함수가 생성할 인스턴스가 바인딩 됨
function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10
apply
/call
this
로 사용할 객체와 인수들을 전달받아 함수를 호출함arguments
와 같은 유사 배열 객체에 대해 배열 메소드를 호출할 때 주로 사용함function printThis() {
console.log(this, arguments);
}
const thisArg = { a: 1 };
printThis.apply(thisArg, [1, 2, 3]); // {a: 1} Arguments(3) [1, 2, 3, callee: (...), Symbol(Symbol.iterator): ƒ]
printThis.call(thisArg, 1, 2, 3); // {a: 1} Arguments(3) [1, 2, 3, callee: (...), Symbol(Symbol.iterator): ƒ]
function convertArgsToArray() {
return Array.prototype.map.call(arguments, arg => arg * 2);
}
console.log(convertArgsToArray(1, 2, 3)); // [2, 4, 6]
bind
this
바인딩이 교체된 새로운 함수를 반환함function printThis() {
console.log(this);
}
const thisArg = { a: 1 };
printThis.bind(thisArg)(); // {a: 1}