✏각각의 객체로 생성하기
const apple = {
name: "apple",
color: "red",
display(){
console.log("apple");
},
};
const orange= {
name: "orange",
color: "orange",
display(){
console.log("orange");
},
};
const banana= {
name: "banana",
color: "yellow",
display(){
console.log("banana");
},
};
✏생성자 함수로 객체 생성하기
function Fruits(name, color){
this.name = name;
this.color = color;
this.display = () => {
console.log(this.name);
};
}
const apple = new Fruits("apple", "red");
const orange = new Fruits("orange", "orange");
const banana= new Fruits("banana", "yellow");
✏class로 객체 생성하기
class Fruits{
constructor(name, color) {
this.name = name;
this.color = color;
}
display = () => {
console.log(this.name);
};
}
const apple = new Fruits("apple", "red");
const orange = new Fruits("orange", "orange");
const banana= new Fruits("banana", "yellow");
🚩constructor(생성자) :
new 키워드로 객체를 생성할때, 호출되는 함수
모든 class는 기본적으로 생성자가 있어야한다.
생성자 안에서 객체를 만드는데 필요한 data를 채운다.
🚩 클래스 안에 필요한 함수 :
생성자 밖에 this 키워드를 삭제하고 적어준다.
function이라는 키워드는 삭제한다.(화살표 함수 ok)
✏ 인스턴스(instence)
//apple이라는 객체는 Fruits라는 클래스의 "인스턴스"이다.
const apple = new Fruits("apple", "red");
//obj는 일반 객체이고, 그 어떤 클래스의 인스턴스도 아니다.
cosnt obj = { name: "Tom" };
🥄 인스턴스
일반적으로 어떤 집합에 대해서, 그 집합의 개별적인 요소.
객체 지향 프로그래밍에서 어떤 등급에 속하는 각 객체를 인스턴스라고 한다.
예를 들면 ‘목록(list)’이라는 등급을 정의하고 그 다음에 ‘본인 목록(my list)’이라는 객체를 생성하면 그 등급의 인스턴스가 생성된다.