클래스, 생성자 (constructor), 객체, 멤버변수(속성,프로퍼티), 멤버 메서드(기능), 인스턴스.
class 와 function 의 다른점
객체지향적 프로그래밍을 하기 위해 이해해야 하는 개념
class의 구조를 이해하고 정의한 방법 공부하기
특정 객체를 생성하기 위해 변수와 메서드(method = 함수 function) 를 정의하는 일종의 설계도 혹은 틀
실제로 메모리에 올라가지는 않음(메모리 누수가 덜함)
클래스로부터 객체를 생성하고 class가 호출될때마다 초기화 과정(멤버변수를 초기화)을 수행하는 메소드. new 연산자를 통해 객체를 생성할때 반드시 호출된다. "constructor" 라는 이름을 가진 특수한 함수는 클래스 안에 한 개만 존재할 수 있다. 클래스에 constructor가 여러개 존재하면 syntaxError 발생
클래스에 정의된 내용대로 생성된 것(속성(=멤버변수)과 기능(=멤버메서드)으로 이루어짐)
클래스로부터 만들어진 객체를 '클래스의 인스턴스' 라고 부른다.
클래스에 속하는 객체를 인스턴스라고 부른다.
클래스로부터 생성된 객체 = 인스턴스
클래스가 메모리공간에 생성된 상태
function과 다른것을 기억하기. 메서드는 특정 객체에 종속된 것으로 객체가 아니지만 function은 객체로 취급된다.
붕어빵 틀 (class)
청사진, 템플릿, 데이터가 들어있지 않고 템플릿만 정의 이런 클래스에는 이런 데이터가 들어올 수 있어.
붕어빵 (object)
클래스를 이용해서 여러개를 만들 수 있다. 팥 -> 팥 붕어빵 크림 -> 크림붕어빵
// Person이라는 클래스를 만들고
class Person {
// constructor (생성자) 를 이용해 object를 만들때 필요한 데이터를 전달한다.
constructor (name,age) {
// 전달받은 데이터를 클래스에 존재하는 두가지 필드 (name,age) 에 바로 할당해준다.
// 클래스에는 name, age 라는 필드가 있고 speak이라는 메소드도 존재한다.
// fields (속성)
this.name = name
this.age = age
}
// methods
speak() {
// this라는것은 생성된 오브젝트를 가리킴
console.log(`${this.name}: hi !`)
}
}
// 이렇게 잘 정의한 클래스를 이용해서 sunny라는 새 object를 만들어보자
const sunny = new Person('sunny',30); // 새로운 사람을 만들거야. constructor 안에 이름과 나이가 전달되면서 새로운 오브젝트 생성
console.log(sunny.name, sunny.age) // sunny, 30
// sunny에는 말하는 메서드가 있기때문에 호출해보자
sunny.speak(); // sunny: hi !
// class
class Person {
constructor(private readonly name: string, private readonly age: number) { }
// 매개변수가 있는 생성자, 매개변수가 없는 생성자 = constructor() {}
public print() {
return `Name: ${this.name}, Age: ${this.age}`
}
}
const mad = new Person('mad', 33) // 객체를 생성할때는 new 연산자를 통해 생성
// Person()은 생성자를 호출한다는 의미이다.
const result = mad.print()
console.log(result)
// function
interface IPerson {
readonly name: string
readonly age: number
}
function person({name, age}: IPerson) {
return `Name: ${name}, Age: ${age}`
}
const mad = person({name: 'mad', age: 33})
console.log(mad)
// Q. 강아지 인스턴스들을 만들고, 콘솔에 강아지의 행동들 찍어보기
// class는 프로퍼티(멤버변수,속성)와 메서드(멤버함수,기능)로 이루어진 어떠한 객체를 만들기 위한 틀, 청사진이다.
class Puppy {
// constructor 생성자 함수, 객체가 생성될때 멤버변수를 초기화 시켜주는 함수, 한 클래스에 하나만
constructor (private breed:string, private name:string,private owner:string, private color:string){}
// 만들어질 객체 (=클래스를 통해 만들어진 객체는 곧 인스턴스) 가 가지고있을 기능
running (){
return `${this.color} ${this.breed} ${this.name} is running to ${this.owner}`
}
sleeping() {
return `${this.breed} is falling asleep on ${this.owner}'s knee`
}
aegyo() {
return `${this.color} ${this.breed} is acting cute to ${this.owner}`
}
}
// 위에 class 틀은 열심히 만들어 놓았으니 new 연산자로 인스턴스들을 만들어보기
const heart = new Puppy('poodle','heart', 'sunny','black')
const zero = new Puppy('jindo','zero','yuri','brown')
console.log(heart.running()) // black poodle heart is running to sunny
console.log(zero.aegyo()) // brown jindo is acting cute to yuri
interface IPuppy {
breed:string;
name:string;
owner:string;
color:string;
}
function running({breed,name,owner,color}:IPuppy){
return `${color} ${breed} ${name} is running to ${owner}`
}
function sleeping ({breed,name,owner,color}:IPuppy){
return `${breed} is falling asleep on ${owner}'s knee`
}
function aegyo ({breed,name,owner,color}:IPuppy){
return `${color} ${breed} is acting cute to ${owner}`
}
console.log(running({breed:'poodle',name:'heart',owner:'sunny',color:'black'}))
// black poodle heart is running to sunny
console.log(sleeping({breed:'jindo', name:'zero',owner:'yuri',color:'silver'}))
// jindo is falling asleep on yuri's knee