Development/JavaScript
JavaScript 클래스 문법
우봉수
2023. 9. 2. 20:20
예전 방식
function Vacation(destination, length){
this.destination = destination
this.length = length
}
Vacation.prototype.print = function(){
console.log(this.destination + "는 "+
this.length)
}
var trip = new Vacation("대구",4)
trip.print()
<출력 결과>
"대구는 4"
최신 방식
class Vacation{
constructor(destination, length){
this.destination = destination
this.length = length
}
print(){
console.log(`${this.destination}은(는)${this.length}일 걸립니다.`)
}
}
var trip = new Vacation("강남",2)
trip.print()
<출력 결과>
"강남은(는)2일 걸립니다."
상속 기능
class Vacation{
constructor(destination, length){
this.destination = destination
this.length = length
}
print(){
console.log(`${this.destination}은(는)${this.length}일 걸립니다.`)
}
}
var trip = new Vacation("강남",2)
trip.print()
class Expedition extends Vacation{
constructor(destination, length, gear){
super(destination,length)
this.gear = gear
}
print(){
super.print()
console.log(`추가 ${this.gear}`)
}
}
var upTrip = new Expedition("강남",2,10)
upTrip.print()
<출력 결과>
"강남은(는)2일 걸립니다."
"강남은(는)2일 걸립니다."
추가 10"