const 객체명 = new 클래스명(인수)
// 클래스 선언하기
function User (country, city) {
this.country = country;
this.city = city;
}
// User 클래스의 프로퍼티를 가지는 객체 생성 : 생성자 함수
const gaji = new User("KOREA", "Busan")
const local = new User("KOREA", "Seoul")
(참고 : https://www.youtube.com/watch?v=wUgmzvExL_E)
객체에 직접 포함되지는 않지만 원할 때 찾아서 사용 가능한거
function User (country, city) {
this.country = country;
this.city = city;
}
User.prototype.getAddress = function () {
return `${this.country} ${this.city}`
}
const gaji = new User("KOREA", "Busan")
gaji // {country: 'KOREA', city: 'Busan'}
gaji.firstName // KOREA Busan
용도

const arr = new Array(1,2,3)
arr.sort() // Array.prototype.sort()
arr.length() // Array.prototype.length()
자주 사용하는 함수 등을 prototype에 저장할 수 있다
※ prototype 함수 작성 시 화살표함수 쓰면 안됨
class User {
constructor (country, city) {
this.country = country;
this.city = city;
}
getAddress = function () {
return `${this.country} ${this.city}`
}
}
객체 안에 직접 만들면 이렇게됨
class User {
constructor (country, city) {
this.country = country;
this.city = city;
this.Address = `${this.country} ${this.city}`
}
}
const gaji = new User("KOREA", "Busan")
// 이사 갔는데 주소가 안바뀜
gaji.city = "Seoul"
gaji // {city : "Seoul", Address: "KOREA Busan"}
class User {
constructor (country, city) {
this.country = country;
this.city = city;
}
get address () {
return `${this.country} ${this.city}`
}
}
const gaji = new User("KOREA", "Busan")
gaji.address // KOREA Busan
gaji.address = "USA LA" // 이민감
gaji // {country: 'KOREA', city: 'Busan'}
gaji.address // KOREA Busan
class User {
constructor (country, city) {
this.country = country;
this.city = city;
}
get address () {
return `${this.country} ${this.city}`
}
// setter 추가
set address (value) {
;[this.country, this.city] = value.split(' ')
}
}
const gaji = new User("KOREA", "Busan")
gaji.address = "USA LA"
gaji // {country: 'USA', city: 'LA'}
클래스에는 프로토타입 메소드와 그냥 (정적) 메소드가 있음
| 프로토타입 | 정적메소드 |
|---|---|
| 인스턴스로 호출 | 클래스로 호출 |
| this로 인스턴스의 프로퍼티를 참조 가능 | this로 인스턴스의 프로퍼티를 참조 가능 |
class User {
constructor (country, city) {
this.country = country;
this.city = city;
}
// 프로토타입
getAddress () {
return `${this.country} ${this.city}`
}
}
const gaji = new User("KOREA", "Busan")
gaji.getAddress() // 인스턴스 호출: KOREA Busan
User.getAddress() // 클래스 호출 : 에러발생
class User {
constructor (country, city) {
this.country = country;
this.city = city;
}
// 정적 메소드
static isUser(name) {
if (name.country && name.city) {
return true
}
return false
}
}
const gaji = new User("KOREA", "Busan")
User.isUser(gaji) // true
User.isUser(local) // false
gaji.isUser() // 인스턴스 호출: 에러발생
class B extends A {
// 내용
}
class A {
constructor(value = 1){
this.value = value // value 기본값 1
}
}
class B extends A {
constructor(value){
super(value) // A의 constructor 상속 받기
}
}
const a = new A()
const b = new B(2)
a // {value: 1}
b // {value: 2}
a instanceof A // true
b instanceof A // true (부모클래스도 ok)
a instanceof B // false
b.constructor === A // false
b.constructor === B // true : b는 B에서 생성된 인스턴스