class?
객체를 만드는 공장.
클래스는 데이터+메소드 로 이루어져 있다.
메소드없이 데이터만 있는 클래스도 있는데 이것은 데이터클래스라고 부른다.
클래스와 객체의 차이
클래스 | 객체 |
템플릿 형식 오직 정의만 할 수 있다. 데이터를 가질 수 없다. ex) 붕어빵 틀 |
class에 데이터를 넣어서 만들어진게 object. ex) 붕어빵 틀에다가 팥과 반죽을 넣고 만들면 = 팥붕어빵 붕어빵 틀에다가 슈크림과 반죽을 넣고 만들면 = 슈크림붕어빵 |
(예시)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
'use strict'
//클래스 만들기//
class person {
// constructor : object를 만들 때 필요한 데이터를 전달
constructor(name,age){
//전달된 데이터를 할당
this.name=name;
this.age=age;
}
//methods
speak() {
console.log(`${this.name}:hello!`);
}
}
const ellie = new person('ellie',20) //클래스를 이용해서 새로운 object를 만들 때 앞에 new를 써준다
console.log(ellie.name); // 결과 : ellie
console.log(ellie.age); // 결과 : 20
ellie.speak(); // 결과 : ellie:hello!
</script>
</html>
https://www.youtube.com/watch?v=_DLhUBWsRtw&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=6