생성자 함수 (prototype)
// 일반 함수와의 차이점을 위해 파스칼 케이스로 함수명 작성
function Student(name, grade) {
this.name = name
this.grade = grade
}
Student.prototype.getStudent = function () {
return `${this.name}는 ${this.grade}입니다`
}
// new 라는 키워드로 생성된 함수를 생성자 함수라고 부름
// 객체 데이터가 생성됨
// yoo, kim, lee 라는 변수는 생성자 함수에 인스턴스라고 부름
const yoo = new Student('Yoo', '4학년')
const kim = new Student('Kim', '3학년')
const lee = new Student('Lee', '2학년')
console.log(yoo.getStudent())
console.log(kim.getStudent())
console.log(lee.getStudent())
this
// this
// 일반(Normal) 함수는 호출 위치에서 this 정의
// 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const yoo = {
name: 'Yoo',
normal: function () {
console.log(this.name)
},
arrow: () => {
console.log(this.name)
}
}
// YOO
yoo.normal()
// undefined
yoo.arrow()
const lee = {
name: 'Lee',
normal: yoo.normal,
arrow: yoo.arrow
}
// Lee
lee.normal()
// undefined
lee.arrow()
// this
// 일반(Normal) 함수는 호출 위치에서 this 정의
// 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
function User(name) {
this.name = name
}
User.prototype.normal = function () {
console.log(this.name)
}
User.prototype.arrow = () => {
console.log(this.name)
}
const yoo = new User('Yoo')
// Yoo
yoo.normal()
// undefined
yoo.arrow()
// this
// 일반(Normal) 함수는 호출 위치에서 this 정의
// 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const timer = {
name: 'Yoo',
timeout: function () {
setTimeout(() => {
console.log(this.name)
}, 2000)
}
}
// Yoo
timer.timeout()
ES6 Classes
// ES6 Classes
// function User(first, last) {
// this.firstName = first
// this.lastName = last
// }
// User.prototype.getFullName = function () {
// return `${this.firstName} ${this.lastName}`
// }
class User {
constructor(first, last) {
this.firstName = first
this.lastName = last
}
getFullNmae() {
return `${this.firstName} ${this.lastName}`
}
}
const lee = new User('jm', 'Lee')
const kim = new User('ms', 'Lee')
console.log(lee)
console.log(kim.getFullNmae())
상속 (확장)
class Venicle {
constructor(name, wheel) {
this.name = name
this.wheel = wheel
}
}
// extends (확장, 상속)
// Venicle 내용을 Bicycle 에 상속한다
// super() = 부모 클래스(Venicle) 생성자 함수를 호출
class Bicycle extends Venicle {
constructor(name, wheel) {
super(name, wheel)
}
}
class Car extends Venicle {
constructor(name, wheel, license) {
super(name, wheel)
this.license = license
}
}