this?
this란 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수이다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
> global 실행 컨텍스트에서 this는 global 객체를 참조한다. 브라우저 호스트 환경에서는 window를, node.js 호스트 환경에서는 global이 되겠다.

> 객체의 메서드 또는 생성자 함수 내부에서 사용할 경우, 함수를 호출한 객체가 this에 참조된다.

때로 this가 원하는 객체를 참조하지 않을 때가 있는데
//예시 1
let user = {
firstName: "John",
sayHi() {
alert(`Hello, ${this.firstName}!`);
}
};
setTimeout(user.sayHi, 1000); //output: Hello, undefined!
//예시 2
const module = {
x: 42,
getX: function() {
return this.x;
}
};
const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
//output: undefined
이럴 때 this가 원하는 객체를 가리키도록 하는 메서드를 알아보자.
1. bind
this.x = 9;
var module = {
x: 81,
getX: function() { return this.x; }
};
module.getX(); // 81
var retrieveX = module.getX;
retrieveX();
// 9 반환 - 함수가 전역 스코프에서 호출됐음
// module과 바인딩된 'this'가 있는 새로운 함수 생성
// 신입 프로그래머는 전역 변수 x와
// module의 속성 x를 혼동할 수 있음
var boundGetX = retrieveX.bind(module);
boundGetX(); // 81
bind는 새로운 함수 객체를 생성하는 메서드이다. bind(this로 참조할 객체, 인자1, 인자2, ...)의 형태로 사용되며, 새로 생성된(바인딩한) 함수는 원본 함수 객체를 감싸는 특이 함수 객체이다. (래핑한다고 하는 그것?! >> 래퍼 함수)
2. call
function Product(name, price) {
this.name = name;
this.price = price;
};
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
};
console.log(new Food('cheese', 5).name);
// output: "cheese"
3. apply
const obj = {
name: 'JY',
};
const hello = function(city) {
console.log(`Hello! my name is ${this.name}, live in ${city}.`);
};
say('seoul'); //output: Hello! my name is , live in seoul.
say.apply(obj, ['busan']); //output: Hello! my name is JY, live in busan.
call과 apply는 함수를 호출하는 메서드이다. bind와 같이 첫 번째 인자에 this에 참조할 객체를 설정하고, 뒤이어 넘겨받을 인자들을 넣어준다. 둘의 가장 큰 차이점은 call(객체, 인수1, 인수2, ...) / apply(객체, [배열 또는 유사배열])의 형태로 인자를 넘겨받는 모양새가 다르다는 점이다.
'[JavaScript]' 카테고리의 다른 글
[javascript] prototype과 __proto__ (0) | 2022.10.03 |
---|---|
[javascript] 생성자 함수와 클래스 (0) | 2022.10.03 |
[javascript] 엘리스 sw 트랙 > 인스타그램 클론 코딩 메모 (1) | 2022.09.26 |
[javascript] DOM의 활용 (0) | 2022.09.22 |
[javascript] inner/outerHTML, textContent 비교 (0) | 2022.09.13 |
댓글