객체지향 프로그래밍 (Object Oriented Programming)에 대하여 알아 보았다.
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; this.fullName = function (hey) { console.log(`${this.firstName} ${this.lastName} ${hey}`); }; } const myself = new Person('wonseok', 'choi'); myself.fullName('ya');
__proto__
를 통해 부모관계를 파악할 수 있다.Object.prototype
와 같다(object 타입의 데이터)Person.prototype.fullName = function (hey) {
console.log(`${this.firstName} ${this.lastName} ${hey}`);
};
일반함수에서의 this -> window
중첩된함수에서의 this -> window
이벤트에서의 this -> 이벤트 객체
특정 객체 내 method에서의 this -> 그 특정 객체
특정 객체 내 method 내의 함수 내 this -> window
즉, 중첩으로 들어간 함수에서의 this는 늘 window 가리킴
이 때, 내가 만약 중첩 함수 내 this가 window가 아닌 해당 object를 가리키게 하고 싶다면, 중첩된 함수 밖에서 const that = this
를 만들어준다. 이 때 this는 해당 object를 가리키게 한다(관례적 해결방법).
아직 완벽하게 prototype과 constructor 개념이 와닿지는 않는다. 아지만 어떤 식으로 자바스크립트가 구성되어 있는 지는 전보다 더 선명하게 이해가 된다.
github에 있다.