- 객체는 상태를 나타내는 프로퍼티와 동작을 나타내는 메서드를 하나의 논리적인 단위로 묶은 복합적인 자료구조이다.
- 동작을 나타내는 메서드는 프로퍼티를 참조하고 변경 가능함. 메서드가 자신이 속한 객체의 프로퍼티를 참조할 때 자신이 속한 객체를 가리키는 식별자를 참조 가능해야한다.
const circle = {
// ✅ 프로퍼티: 객체 고유의 상태 데이터
radius: 5,
// ✅ 메서드: 상태 데이터를 참조하고 조작하는 동작
getDiameter() {
// this는 메서드를 호출한 객체를 가리킨다.
return 2 * this.radius;
},
};
console.log(circle.getDiameter()); // 10🚨 자기 자신이 속한 객체를 재귀적으로 참조하는 방식은 일반적이지 않다.
👉 대신, 생성자 함수 방식으로 인스턴스를 생성하는 경우 차용
- this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수로 프로퍼티나 메서드를 참조할 수 있다.
- this는 엔진에 의해 암묵적으로 생성되고 어디서든 참조 가능하다. 함수 호출 시 arguments 객체와 this가 암묵적으로 함수 내부에 전달되어, 함수 내부에서도 arguments 객체를 지역변수처럼 쓰는 것과 같이 this도 사용 가능하다. 👉 this 바인딩(this가 가리키는 값)은 함수 호출 방식에 의해 동적으로 결정됨.
- strict mode 적용시, 일반 함수 내부의 this에는 undefined가 바인딩된다. => this는 객체의 메서드 내부 또는 생성자 함수 내부에서만 의미가 있으므로..
// 생성자 함수
function Circle(radius) {
// this는 생성자 함수가 생성할 인스턴스를 가리킨다.
this.radius = radius;
}
Circle.prototype.getDiameter = function () {
// this는 생성자 함수가 생성할 인스턴스를 가리킨다.
return 2 * this.radius;
};
// 인스턴스 생성
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10// this는 어디서든지 참조 가능하다.
// 전역에서 this는 전역 객체 window를 가리킨다.
console.log(this); // window
function square(number) {
// 일반 함수 내부에서 this는 전역 객체 window를 가리킨다.
console.log(this); // window
return number * number;
}
square(2);
const person = {
name: "Lee",
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
console.log(this); // {name: "Lee", getName: ƒ}
return this.name;
},
};
console.log(person.getName()); // Lee
function Person(name) {
this.name = name;
// 생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
console.log(this); // Person {name: "Lee"}
}
const me = new Person("Lee");❓바인딩이란
- 식별자와 값을 연결하는 과정
- this와 this가 가리킬 객체를 바인딩하는 것
this 바인딩은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
렉시컬 스코프:
- 함수가 선언된 위치에서 결정되는 스코프
- 함수가 어디에서 호출되었는지가 아니라 어디에서 정의되었는지에 따라 변수의 스코프(유효 범위)가 결정된다.
this 바인딩:
- 함수를 호출한 방식에 따라 달라지는 동적 바인딩을 가짐. (바인딩은 컴퓨터 프로그램에서 값과 식별자 사이의 연관 관계)
- this가 가리키는 객체는 함수가 호출될 때 결정된다.
👉 동일한 함수를 다양한 방식으로 호출 가능하다.
-
기본적으로 this에는 전역 객체가 바인딩되는데, 중첩 함수를 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩된다.
-
this는 자기 참조 변수이므로 객체를 생성하지 않는 일반 함수에서는 의미가 없다. 예를 들어,
strict mode에서는undefined가 바인딩된다.
function foo() {
"use strict";
console.log("foo's this: ", this); // undefined
function bar() {
console.log("bar's this: ", this); // undefined
}
bar();
}
foo();- 콜백 함수가 일반 함수로 호출 시, 콜백 함수 내부의 this에도 전역 객체가 바인딩된다. 어떠한 함수라도 일반 함수로 호출 시, this에 전역 객체(window)가 바인딩된다.
// var 키워드로 선언한 전역 변수 value는 전역 객체의 프로퍼티다.
var value = 1;
// const 키워드로 선언한 전역 변수 value는 전역 객체의 프로퍼티가 아니다.
// const value = 1;
const obj = {
value: 100,
foo() {
console.log("foo's this: ", this); // {value: 100, foo: ƒ}
console.log("foo's this.value: ", this.value); // 100
// 메서드 내에서 정의한 중첩 함수
function bar() {
console.log("bar's this: ", this); // window
console.log("bar's this.value: ", this.value); // 1
}
// 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this에는 전역 객체가 바인딩된다.
bar();
},
};
obj.foo();- 일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this에는 전역 객체가 바인딩된다.
⚠️ 일반 함수로 호출될 때, 메서드 내 중첩 함수 또는 콜백 함수의 this가 전역 객체를 바인딩할 때 문제가 생길 수 있음. 외부 함수인 메서드와 중첩 함수 또는 콜백 함수의 this가 일치하지 않을 때, 중첩 함수 또는 콜백 함수를 헬퍼 함수로 동작하기 어렵게 만들 수가 있음.
var value = 1;
const obj = {
value: 100,
foo() {
console.log("foo's this: ", this); // {value: 100, foo: ƒ}
// 콜백 함수 내부의 this에는 전역 객체가 바인딩된다.
setTimeout(function () {
console.log("callback's this: ", this); // window
console.log("callback's this.value: ", this.value); // 1
}, 100);
},
};
obj.foo();
setTime()
- 두번쨰 인수로 전달한 시간(ms)만큼 대기한 다음, 첫번째 인수로 전달한 콜백 함수를 호출하는 타이머 함수
- this가 일치하지 않는 문제 예제
const obj = {
name: "Alice",
showName: function () {
console.log("메서드 내부 this.name:", this.name); // "Alice"
function innerFunction() {
console.log("중첩 함수 내부 this.name:", this.name); // undefined (strict mode) 또는 window.name
}
innerFunction(); // 일반 함수로 호출되므로 `this`가 전역 객체를 가리킴
},
};
obj.showName();- 콜백 함수에서 this 문제
const obj = {
name: "Alice",
showName: function () {
setTimeout(function () {
console.log("setTimeout 내부 this.name:", this.name); // undefined
}, 1000);
},
};
obj.showName();👉 해결책 1. self(or that) 변수 사용
- self에 this(현재 객체)를 저장하고 중첩 함수에서 self를 사용하여 객체 속성에 접근
const obj = {
name: "Alice",
showName: function () {
const self = this; // `this`를 저장
function innerFunction() {
console.log("중첩 함수 내부 this.name:", self.name); // "Alice"
}
innerFunction();
},
};
obj.showName();해결책 2. bind() 메서드 사용
const obj = {
name: "Alice",
showName: function () {
function innerFunction() {
console.log("중첩 함수 내부 this.name:", this.name); // "Alice"
}
const boundInnerFunction = innerFunction.bind(this); // `this`를 obj로 고정
boundInnerFunction();
},
};
obj.showName();해결책 3. 화살표 함수 사용
- 화살표 함수는 this를 상위 스코프의 this를 그대로 계승하므로, 중첩 함수에서 문제가 발생하지 않는다.
const obj = {
name: "Alice",
showName: function () {
const innerFunction = () => {
console.log("중첩 함수 내부 this.name:", this.name); // "Alice"
};
innerFunction();
},
};
obj.showName();해결책 4. call() 또는 apply() 사용
- this를 명시적으로 지정하여 호출
const obj = {
name: "Alice",
showName: function () {
function innerFunction() {
console.log("중첩 함수 내부 this.name:", this.name); // "Alice"
}
innerFunction.call(this); // `this`를 obj로 설정
},
};
obj.showName();- 메서드 내부의 this는 메서드를 호출한 객체(메서드 이름 앞의 마침표(.) 연산자 앞에 기술한 객체)가 바인딩된다. 메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다는 것이다.
const person = {
name: "Lee",
getName() {
// 메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.
return this.name;
},
};
// 메서드 getName을 호출한 객체는 person이다.
console.log(person.getName()); // Lee- getName 프로퍼티가 가리키는 함수인 getName 메서드는 다른 객체의 프로퍼티에 할당하는 것으로 다른 객체의 메서드가 될 수 있음. 또한, 일반 함수에 할당하여 일반 함수로 호출될 수도 있음.
- 메서드 내부의 this는 프로퍼티로 메서드를 가리키고 있는 객체와 관계가 없고 메서드를 호출한 객체에 바인딩됨.
const anotherPerson = {
name: "Kim",
};
// getName 메서드를 anotherPerson 객체의 메서드로 할당
anotherPerson.getName = person.getName;
// getName 메서드를 호출한 객체는 anotherPerson이다.
console.log(anotherPerson.getName()); // Kim
// getName 메서드를 변수에 할당
const getName = person.getName;
// getName 메서드를 일반 함수로 호출
console.log(getName()); // ''
// 일반 함수로 호출된 getName 함수 내부의 this.name은 브라우저 환경에서 window.name과 같다.
// 브라우저 환경에서 window.name은 브라우저 창의 이름을 나타내는 빌트인 프로퍼티이며 기본값은 ''이다.
// Node.js 환경에서 this.name은 undefined다.function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
};
const me = new Person("Lee");
// getName 메서드를 호출한 객체는 me다.
console.log(me.getName()); // ① Lee
Person.prototype.name = "Kim";
// getName 메서드를 호출한 객체는 Person.prototype이다.
console.log(Person.prototype.getName()); // ② Kim- 생성자 함수 내부의 this에는 생성자 함수가 생성할 인스턴스가 바인딩된다.
// 생성자 함수
function Circle(radius) {
// 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// 반지름이 5인 Circle 객체를 생성
const circle1 = new Circle(5);
// 반지름이 10인 Circle 객체를 생성
const circle2 = new Circle(10);
console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20메서드 함수란?
- 메서드 함수는 객체의 프로퍼티로 정의된 함수로, 해당 객체의 속성을 읽거나 수정하는 기능을 수행합니다.
📌 특징
- 객체의 속성과 연관된 동작을 수행하는 함수
- 객체의 메서드로 호출될 때, this는 해당 객체를 가리킴.
- new 키워드 없이 호출
생성자 함수란?
- 생성자 함수는 새로운 객체를 만들기 위한 함수로, new 키워드와 함께 호출됩니다.
📌 특징
- 새로운 객체(인스턴스)를 생성하는 용도
- new 키워드를 사용하여 호출할 때, this가 새롭게 생성된 객체를 가리킴.
- 생성자 함수의 이름은 대문자로 시작하는 것이 관례 (PascalCase)
apply, call, bind메서드는Function.prototype.apply의 메서드로 모든 함수가 상속받아 사용 가능- apply, call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달 받아 함수를 호출한다.
function getThisBinding() {
return this;
}
// this로 사용할 객체
const thisArg = { a: 1 };
console.log(getThisBinding()); // window
// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩한다.
console.log(getThisBinding.apply(thisArg)); // {a: 1}
console.log(getThisBinding.call(thisArg)); // {a: 1}👉 위 예제처럼 apply와 call의 본질적인 기능 == 함수 호출 apply와 call 메서드는 호출할 함수에 인수를 전달하는 방식만 다를 뿐 동일하게 동작한다.
차이점:
- apply는 인수를 배열로 묶어 전달한다. call은 쉼표로 구분한 리스트 형식으로 전달한다.
function getThisBinding() {
console.log(arguments);
return this;
}
// this로 사용할 객체
const thisArg = { a: 1 };
// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩한다.
// apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달한다.
console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a: 1}
// call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달한다.
console.log(getThisBinding.call(thisArg, 1, 2, 3));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// {a: 1}- apply와 call 메서드의 대표적인 용도는 arguments와 같은 유사 배열 객체에 배열 메서드를 사용하는 경우: arguments 객체는 배열이 아니므로 Array.prototype.slice와 같은 배열의 메서드를 사용 못하나 apply, call 메서드에서는 가능하다.
🌟 bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.
function getThisBinding() {
return this;
}
// this로 사용할 객체
const thisArg = { a: 1 };
// bind 메서드는 첫 번째 인수로 전달한 thisArg로 this 바인딩이 교체된
// getThisBinding 함수를 새롭게 생성해 반환한다.
console.log(getThisBinding.bind(thisArg)); // getThisBinding
// bind 메서드는 함수를 호출하지는 않으므로 명시적으로 호출해야 한다.
console.log(getThisBinding.bind(thisArg)()); // {a: 1}- person.foo의 콜백 함수가 호출되기 이전(① 시점)에 this가 person 객체를 가리킨다. 그러나. person.foo의 콜백 함수가 일반 함수로서 호출된 ② 시점에서 this는 전역 객체 window를 가리킨다.
const person = {
name: "Lee",
foo(callback) {
// ① this => person
setTimeout(callback, 100);
},
};
person.foo(function () {
console.log(`Hi! my name is ${this.name}.`); // ② Hi! my name is undefined.
// 일반 함수로 호출된 콜백 함수 내부의 this.name은 브라우저 환경에서 window.name과 같다.
// 브라우저 환경에서 window.name은 브라우저 창의 이름을 나타내는 빌트인 프로퍼티이며 기본값은 ''이다.
// Node.js 환경에서 this.name은 undefined다.
});해결하는 코드:
- person.foo의 콜백함수는 외부 함수 person.foo의 헬퍼 함수의 역할이므로, this가 상이하면 문제가 발생한다.(위 예제처럼)
따라서, 콜백 함수 내부의 this를 외부 함수 내부의 this와 일치시켜야한다.
=>
bind메서드 사용
const person = {
name: "Lee",
foo(callback) {
// bind 메서드로 callback 함수 내부의 this 바인딩을 전달
setTimeout(callback.bind(this), 100);
},
};
person.foo(function () {
console.log(`Hi! my name is ${this.name}.`); // Hi! my name is Lee.
});

