메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 자신이 속한 객체를 가리키는 식별자를 참조 할 수 있어야 한다.
const circle = {
radius: 5,
getDiameter(){ return 2 * circle.radius }
}
console.log(circle.getDiameter()) // 10
생성한 객체의 경우 메서드 내부에서 메서드 자신이 속한 객체를 가리키는 식별자를 재귀적으로 참조할 수 있다.
getDiameter 메서드가 호출되는 시점에는 이미 객체 리터럴의 평가가 완료되어 객체가 생성되어 객체가 생성되었고, circle 식별자에 생성된 객체가 할당된 이후다.
자기 자신이 속한 객체를 재귀적으로 참조하는 방식은 일방적이지 않으며 바람직하지 않다.
function Circle(radius){
????.radius = radius // 이 시점에는 생성자 함수 자신이 생성할 인스턴스를 가리키는 식별자를 알 수 없다.
}
Circle.prototype.getDiameter = function(){
return 2 * ????.radius; // 이 시점에는 생성자 함수 자신이 생성할 인스턴스를 가리키는 식별자를 알 수 없다.
}
const circle = new Circle(5); // 생성자 함수로 인스턴스를 생성하려면 먼저 생성자 함수를 정의해야 한다.
이를 위해 자바스크립트는 this
라는 특수한 식별자를 제공한다!
this
: 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this 바인딩
: this와 this가 가리킬 객체를 바인딩하는 것
this 바인딩은 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
렉스컬 스코프
: 함수 객체 생성되는 시점에 결정
this 바인딩
: 함수 호출 시점에 결정
일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this에는 전역 객체가 바인딩 된다.
사용하고 싶다면?
1. this를 변수에 할당해서 참조하게 한다. ex) const that = this
2. apply, call, bind
3. 화살표 함수를 사용해서 this 바인딩을 일치
메서드 내부의 this는 프로퍼티로 메서드를 가리키고 있는 객체와는 관계가 없고, 메서드를 호출한 객체에 바인딩 된다.
function Person(name){
this.name = name;
}
Person.prototype.getName = function (){ return this.name };
const me = new Person('Lee');
console.log(me.getName()) // 객체 : me , Lee
Person.prototype.name = 'kim';
console.log(Person.prototype.getName()) // 객체 : Person.prototype , kim
생성자 함수 내부의 this에는 생성자 함수가 (미래에) 생성할 인스턴스가 바인딩된다.
function Test(num){
this.num = num;
this.getNum = function () { return this.num * 2};
}
const num1 = new Test(1);
console.log(num1.getNum()) // 객체 : num1 , 2
const num2 = new Test(2);
console.log(num2.getNum()) // 객체 : num2 , 4
apply, call, bind 메서드는 Function.prototype의 메서드다.
apply, call 의 본질적인 기능은 함수를 호출하는 것.
let a = {
name: 'a'
}
let b = {
name: 'b',
sayHi: function(){
console.log(`마! 내 부산사는 ${this.name}이다! 반갑다!`);
}
}
let c = {
name: 'c'
}
b.sayHi(); // 마! 내 부산사는 b이다! 반갑다!
b.sayHi.call(a) // 마! 내 부산사는 a이다! 반갑다!
b.sayHi.apply(c) // 마! 내 부산사는 c이다! 반갑다!
call => function.call(thisArg[, arg1[, arg2[, ...]]])
apply => function.apply(thisArg, [argsArray])
function convertArgsToArray() {
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
console.log(arguments);
const arr1 = Array.prototype.slice.call(arguments);
const arr2 = Array.prototype.slice.apply(arguments);
return [arr1, arr2];
}
convertArgsToArray(1,2,3) // [[1,2,3], [1,2,3]]
apply, call 대표적인 용도 -> arguments 객체와 같은 유사 배열 객체에 배열 메서드를 사용하는 경우
const person = {
name: 'lee',
foo(callback){
setTimeout(callback.bind(this), 100);
}
}
person.foo(function(){
console.log(`Hi! my name is ${this.name}`) // Hi! my name is lee
});
bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.
함수 호출 방식 | this 바인딩 |
---|---|
일반 함수 호출 | 전역 객체 |
메서드 호출 | 메서드를 호출한 객체 |
생성자 함수 호출 | 생성자 함수가 (미래에) 생성할 인스턴스 |
apply/call/bind메서드에 의한 간접 호출 | apply/call/bind 메서드에 첫번째 인수로 전달한 객체 |