자바스크립트는 명령형, 함수형, 프로토타입 기반, 객체지향 프로그래밍을 지원하는
멀티 패러다임 프로그래밍 언어다.자바스크립트를 이루고 있는 거의 "모든 것"이 객체다
객체지향 프로그래밍
: 객체의 상태
를 나타내는 데이터와 상태 데이터를 조작할 수 있는 동작
을 하나의 논리적인 단위로 묶어 생각한다.
따라서 객체는 상태 데이터와 동작을 하나의 논리적인 단위로 묶은 복잡적인 자료구조라고 할 수 있다.
이때 객체의 상태 데이터를 프로퍼티, 동작을 메서드라고 부른다.
상속
: 어떤 객체의 프로퍼티 또는 메서드를 다른 객체가 상속받아 그대로 사용할 수 있는 것
자바스크립트는 프로토타입을 기반으로 상속을 구현한다. (쓸까 싶었지만, 회사에서 쓰는거 한번 봤다..!)
function testFunc(num){
this.num = num;
}
testFunc.prototype.getNum = function(){
return this.num
}
const test1 = new testFunc();
const test2 = new testFunc();
상속은 코드의 재사용이란 관점에서 매우 유용!
프로토타입 객체
: 객체지향 프로그래밍의 근간을 이루는 객체 간 상속을 구현하기 위해 사용된다.
구분 | 소유 | 값 | 사용 주체 | 사용 목적 |
---|---|---|---|---|
__proto__접근자 프로퍼티 | 모든 객체 | 프로토타입의 참조 | 모든 객체 | 객체 자신의 프로토타입에 접근 또는 교체하기 위해 사용 |
prototype 프로퍼티 | constructor | 프로토타입의 참조 | 생성자 함수 | 생성자 함수가 생성할 객체(인스턴스)의 프로토타입을 할당하기 위해 사용 |
function Foo() {}
const fooInstance = new Foo();
console.log(fooInstance.__proto__ === Foo.prototype); // true
Foo.prototype = { newPrototypeProp: 123 };
console.log(fooInstance.__proto__ === Foo.prototype); // false
모든 프로토타입은 constructor 프로퍼티를 갖는다.
function Test(num){
this.num = num;
}
const test1 = new Test(1);
console.log(test1.constructor === Test) // true
// obj 객체는 Object 생성자 함수로 생성한 객체가 아니라 객체 리터럴로 생성했다.
const obj = {};
// 하지만 obj 객체의 생성자 함수는 Object 생성자 함수다.
console.log(obj.constructor === Object); // true
Object 생성자 함수에 인수를 전달하지 않거나 undefined 또는 null을 인수로 전달하면서 호출하면 Object.prototype을 프로토타입으로 갖는 빈 객체를 생성한다. (추상연산 OrdinaryObjectCCreate)
객체 리터럴이 평가될 때는 빈 객체를 생성하고 프로퍼티를 추가하도록 되어있는데, 이점은 생성자 함수와 동일하지만 new.target의 확인이나 프로퍼티 추가하는 처리 세부 내용이 다기 때문에 객체리터럴은 Object생성자 함수가 생성한 객체가 아니다.
리터럴로 생성된 객체도 상속을 위해 프로토타입이 필요하기 때문에 가상적인 생성자 함수
를 갖는다. 프로토타입은 생성자 함수와 더불어 생성되며 prototype, constructor 프로퍼티에 의해 연결되어 있기 때문이다.
=> 프로토타입과 생성자함수는 단독으로 존재할 수 없고 언제나 쌍으로 존재한다.
프로토타입은 생성자 함수가 생성되는 시점에 더불어 생산된다.
console.log(Person.prototype) // {constructor: f}
function Person(name){
this.name = numname
}
객체가 생성되기 이전에 생성자 함수와 프로토타입은 이미 객체화 되어 존재한다.
이후 생성자 함수 또는 리터럴 표기법으로 객체를 생성하면 프로토타입은 생성된 객체의 [[Prototype]] 내부 슬롯에 할당 된다. 이로써 생성된 객체는 프로토타입을 상속받는다.
console.log(window.object === Object) // true
객체 생성 방법
방식마다 세부적인 객체 생성 방식의 차이는 있으나,
추상 연산 OrdinaryObjectCreate에 의해 생성된다는 공통점이 있다.
프로토타입은 추상 연산 OrdinaryObjectCreate에 전달되는 인수에 의해 결정된다.
이 인수는 객체가 생성되는 시점에 의해 결정된다.
const obj = {x: 1};
console.log(obj.constructor === Object); // true
console.log(obj.hasOwnProperty('x')); // true
const obj = new Object();
obj.x = 1;
console.log(obj.constructor === Object); // true
console.log(obj.hasOwnProperty('x')); // true
객체 리터럴과 Object 생성자 함수에 의한 객체 생성 방식의 차이 : 프로퍼티를 추가하는 방식
function Person(name){
this.name = name;
}
const me = new Person('Lee');
function Person(name){
this.name = name;
}
Person.prototype.sayName = function () {
console.log(${this.name});
}
const me = new Person('Lee');
me.sayName(); // 'Lee'
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`);
};
const me = new Person('Lee');
console.log(me.hasOwnProperty('name')); // true
console.log(Object.getPrototypeOf(me) === Person.prototype); // true
console.log(Object.getPrototypeOf(Person.prototype) === Object.prototype); // true
프로토타입 체인
: 자바스크립트는 객체의 프로퍼티(메서드 포함)에 접근하려 할 때 해당 객체에 접근하려는 프로퍼티가 없다면 [[Prototype]] 내부 슬롯의 참조를 따라 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순차적으로 검색한다.
프로토타입 체인은 상속과 프로퍼티 검색을 위한 메커니즘
스코프 체인은 식별자 검색을 위한 메커니즘
=> 스코프 체인과 프로토타입 체인은 서로 협력하여 식별자와 프로퍼티를 검색하는 데 사용된다.
// 생성자 함수
function Person(name) {
this.name = name;
}
// 프로토타입 메서드
Person.prototype.sayHello = function () {
console.log(`Hi! My name is ${this.name}`);
}
const me = new Person('Lee');
// 인스턴스 메서드
me.sayHello = function () {
console.log(`Hey! My name is ${this.name}`);
}
me.sayHello(); // Hey! My name is Lee
delete me.sayHello
me.sayHello(); // Hi! My name is Lee
// 하위 객체를 통해 프로토타입에 get액세스는 허용되나, set 액세스는 호용되지 않는다.
// 프로토타입에 직접 접근해야한다.
delete me.sayHello
me.sayHello(); // Hi! My name is Lee
프로퍼티 섀도잉
이라 한다.오버라이딩
: 상위 클래스가 가지고 있는 메서드를 하위 클래스가 재정의하여 사용하는 방식
오버로딩
: 함수의 이름은 동일하지만 매개변수의 타입 또는 개수가 다른 메서드를 구현하고 매개변수에 의해 메서드를 구별하여 호출하는 방식이다. 오버로딩을 지원하지 않지만, arguments 객체를 사용하여 구현할 수는 있다.
프로토타입은 부모 객체인 프로토타입을 동적으로 변경할 수 있다.
이러한 특징을 활용하여 객체 간의 상속 관계를 동적으로 변경할 수 있다.
function Person(name) {
this.name = name;
}
Person.prototype = {
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
const me = new Person('Lee');
console.log(me.constructor === Person); // false
console.log(me.constructor === Object); // true
// 프로토타입으로 교체하면 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴된다.
Person.prototype = {
constructor : Person, // 이것을 추가해줘야 한다.
sayHello() {
console.log(`Hi! My name is ${this.name}`);
}
};
console.log(me.constructor === Person); // true
console.log(me.constructor === Object); // false
function Person(name){
this.name = name;
}
const me = new Person('Lee');
const parent = {
sayHello(){
console.log(`Hi! my name is ${this.name}`)
}
}
Object.setPrototypeOf(me, parent);
me.sayHello() // Hi! my name is Lee
console.log(me.constructor === Person); // false
console.log(me.constructor === Object); // true
// 또 Object로 바뀜
함수에 의한 교체와 인스턴스에 의한 교체
instanceOf 연산자
: 우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 프로토타입 체인 상에 존재하면 true로 평가되고, 그렇지 않은 경우에는 false로 평가된다.
function Person(name){
this.name = name;
}
const me = new Person('Lee');
console.log(me instanceof Person) // true
console.log(me instanceof Object) // true
const parent = {};
Object.setPrototypeOf(me, parent);
console.log(Person.prototype === parent) // false
console.log(parent.constructor === parent) // false
// Person.prototype이 me 객체의 프로토타입 체인 상에 존재하지 않는다.
console.log(me instanceof Person) // false
console.log(me instanceof Object) // true
// 생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인 상에 존재하는지 확인한다.
Person.prototype = parent;
console.log(me instanceof Person) // true
console.log(me instanceof Object) // true
function isInstanceof(instance, constructor){
const prototype = Object.getPrototypeOf(instance);
if(prototype === null) return false;
return prototype === constructor.prototype || isInstanceof(prototype, constructor);
}
console.log(isInstanceof(me, Person)); // true
console.log(isInstanceof(me, Object)); // true
console.log(isInstanceof(me, Array)); // false
Object.create
: 명시적으로 프로토타입을 지정하여 새로운 객체를 생성한다.
/**
* 지정된 프로토타입 및 프로퍼티를 갖는 새로운 객체를 생성하여 반환한다.
* @param {Object} prototype - 생성할 객체의 프로토타입으로 지정할 객체
* @param {Object} [propertiesObject] - 생성할 객체의 프로퍼티를 갖는 객체
* @returns {Object} 지정된 프로토타입 및 프로퍼티를 갖는 새로운 객체
*/
Object.create(prototype[, propertiesObject])
ES6에서는 객체 리터럴 내부에서 __proto__ 접근자 프로퍼티를 사용하여 직접 상속을 구현할 수 있다.
정적 프로퍼티/메서드
: 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드를 말한다.
function Person(name) {
this.name = name;
}
Person.staticProp = 'static prop';
Person.staticMethod = function () {
console.log('staticMethod');
};
정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.
in 연산자
: 객체 내에 특정 프로퍼티가 존재하는지 여부를 확인한다.
const person = {name:'Lee'};
console.log(Reflect.has(person, 'name')); // true
console.log(Reflect.has(person, 'toString')); // true
const person = {name:'Lee'};
console.log(person.hasOwnProperty('name')); // true
console.log(person.hasOwnProperty('age')); // false
for...in문
: 객체의 프로토타입 체인 상에 존재하는 모든 프로토타입의 프로퍼티 중에서 프로퍼티 어트리뷰트[[Enumerable]]의 값이 true인 프로퍼티를 순회하며 열거한다.
const person = {
name: 'Lee',
address: 'Seoul',
__proto__: { age: 20 }
};
console.log(Object.entries(person)); // [['name', 'Lee'], ['address', 'Seoul']]
Object.entries(person).forEach(([key, value]) => console.log(key, value)); // name Lee, address Seoul
객체 자신의 고유 프로퍼티만 열거하기 위해서는 for...in 보다는 Object.keys/values/entries 메서드 추천