https://www.yes24.com/Product/Goods/92742567
모던 자바스크립트 Deep Dive - 예스24
『모던 자바스크립트 Deep Dive』에서는 자바스크립트를 둘러싼 기본 개념을 정확하고 구체적으로 설명하고, 자바스크립트 코드의 동작 원리를 집요하게 파헤친다. 따라서 여러분이 작성한 코드
www.yes24.com
공부하면서 정리한 글입니다.
this는 자신이 속한 객체 또는 자신이 생성할 인스터를 가리키는 자기 참조 변수 self-referencing variable다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드(함수)를 참조할 수 있다.
여기서 프로퍼티는 객체의 집합이며 키와 값으로 구성되어 있다.
ex) var book = {
title : 'ModerJavaScriptDeepDive', --> 프로퍼티 키 ModerJavaScriptDeepDive
price:45000 --> 프로퍼티 값 45000
};
this를 이용하여 프로퍼티를 참조 할 때는 this.title, this.price dot(점)을 붙여 사용한다.
생성자 함수 인스턴스
// 생성자 함수
function Book(price) {
// this는 생성자 함수가 생성할 인스턴스를 가리킨다.
this.price = price;
}
Book.prototype.bonus = function() {
// this는 생성자 함수가 생성할 인스턴스를 가리킨다.
return 2 * this.price
}
// 인스턴스 7 생성
const book = new Book(7)
// 인스턴스의 bonus 메서드(함수)를 참조해서 this.price = 7의값에 2를 곱한 14가 나온다.
console.log(book.bonus());
전역객체, 메서드 내부 this호출, 생성자함수
console.log(this); // 전역객체 window
function double(number) {
console.log(this) // 전역객체 window를 가리킨다.
return number * number;
}
double(2);
const person = {
name: 'Hongsun',
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체 즉 person의 객체를 가리킨다.
console.log(this);
return this.name;
}
};
// {name:'Hongsun', getName:f}
// Honsun
console.log(person.getName());
function Person(name) {
this.name = name;
// 생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
// Person {name:"Kim"}
console.log(this);
}
// 인스턴스 'Kim' 생성
const me = new Person('Kim');