1️⃣ 팩토리와 클래스
2️⃣ new, 생성자, instanceof, 인스턴스
3️⃣ Object.create와 Object.assign
5️⃣ 프로토타입의 상속과 체인
팩토리 함수 (Factory Function)
function createJelly() {
return {
type: 'jelly',
colour: 'red'
scoops: 3
};
}
function createIceCream(flavour='Vanilla') {
return {
type: 'icecream',
scoops: 3,
flavour
}
}
function createDessert() {
return {
type: 'dessert',
bowl: [
createJelly(),
createIceCream()
]
};
}
클래스(Class)
class
라는 문법은 C, Java 등에서 이미 사용되는 문법이지만 JavaScript에서는 없었다.
JavaScript에서는 그 대체제로 사용됐던 것이 생성자 함수였다.class
문법이 도입되었다.class Person {
constructor(name, age, number) {
this.name = name;
this.age = age;
this.number = number;
};
intro() {
console.log("잘 부탁드립니다!")
};
};
let kim = new Person("KIM", 30, 1);
kim.intro = function() {
console.log("경주 김씨입니다. 잘 부탁드립니다!");
};
console.log(kim); // {name: "KIM", age:30, number:1}
class
블록 안에 constructor
함수를 추가하고 인자와 함수 내용을 작성하면 된다.class
내의 constructor
함수는 객체가 생성될 때 무조건적으로 자동 실행한다.class
에 prototype
으로 메소드를 만드는 방법에는 두 가지가 있다.
class
외부에서 prototype
을 선언해서 함수를 만드는 방법**class
안에서 함수를 선언해서 만드는 방법**
class
에서는 이 방법을 권장하며 class 안에서 만들어지는 함수는 기본적으로 prototype
이 세팅된다.kim
에 있는 intro
라는 메소드가 class
외부에서 새로 지정되어있다면 해당 내용을 우선적으로 적용한다.
그러나 없다면 class
안에 있는 prototype
메소드인 intro
를 적용한다.이전에 학습했던 내용이 있어 해당 내용을 그대로 가져왔다.
**new
와 생성자 함수**
**new
연산자를 이용함**으로서 기존의 함수 내용을 새로운 객체로 만들어낼 수 있다.
function Person(){
this.first=name;
this.second=first;
this.sum = function(){
return this.first+this.second;
}
}
console.log(Person()); // 함수 내에 return되는 값이 없으므로 undefined가 나온다.
console.log(new Person());
// new라는 키워드를 붙이면 객체를 생성하는 생성자 함수가 되면서 객체의 내용이 출력된다.
이처럼 new
연산자를 함수에 붙이게 되면 해당 함수는 더 이상 함수가 아닌 객체로 취급하는 ‘생성자 함수’가 된다.
생성자 함수를 통해 우리는 기존 객체와 유사한 객체들을 만들어 낼 수 있고, 또 이를 이용해 객체 내부를 변화시킴으로서 확장시킬 수도 있다.
생성자 함수를 만들 때에는 두 가지의 규칙을 지켜야 한다.
생성자 함수는 객체를 만들어내는 함수이기 때문에, 값을 수정하고 싶을 경우 아래와 같이 함수처럼 인자로 값을 받아와 객체의 정보를 변경해줄 수 있다.
function Person(name, first, second, third){
this.name=name;
this.first=first;
this.second=second;
this.sum = function(){
return this.first+this.second;
}
}
var kim = new Person('kim', 10, 20);
var lee = new Person('lee', 10, 10);
console.log("kim.sum()", kim.sum()); // "kim.sum()" 30;
console.log("lee.sum()", lee.sum()); // "lee.sum()" 20;
생성자 함수를 사용하면 같은 형태를 가지지만 다양한 값을 가진 객체를 편하게 생성해낼 수 있으며, 생성자 함수의 내용을 수정하면 이를 통해 생성한 객체들에도 수정된 정보가 반영되므로 일괄적으로 관리할 수 있다는 장점이 있다.
인스턴스(instance)와 instanceof
**new
연산자를 이용해서 class나 생성자 함수를 통해** 생성한 객체가 인스턴스에 속한다고 볼 수 있다.**instanceof**
instanceof는 생성된 인스턴스 객체가 어떤 class나 생성자 함수를 사용하여 생성됐는지를 판단해주는 연산자이다.
function Person(name) {
this.name = name;
}
class Pokemon {
constructor(name){
this.name = name;
}
}
const newPerson = new Person('Satoshi');
const newPokemon = new Pokemon ('Diaruga');
console.log(newPerson instanceof Person)
// true
console.log(newPerson instanceof Pokemon)
// false
console.log(newPokemon instanceof Pokemon)
// true
이렇게 확인하고자 하는 대상 객체의 prototype
속 생성자(constructor
) 속성을 확인하여 해당 생성자가 동일하다면 true
를, 아니면 false
를 반환한다.