❕ 자바스크립트는 프로토타입 기반 언어
❕ 프로토타입은 객체의 원형
function Student(name) {// 클래스
this.name = name
}
const me = new Student('sunny')
console.log(me)
클래스란❓ 개념의 단위, 개념을 하나로 묶는 느낌쓰, 덩어리
함수를 정의하듯이 클래스 만들고 있다.
클래스? 👉 prototype을 기반으로 한 function?
new를 통해 함수를 부르게 되면 함수는 생성자로서의 역할을 하게 됨
this는 새로 만들어지는 object에 binding됨❗
function Student(name) {
this.name = name
}
Student.prototype.greet = function greet(){
return `Hi, ${this.name}` // 이 this는 greet을 호출한 객체에 연결
// 그 객체에서 name값 가져옴
}
const me = new Student('sunny')
console.log(me.greet())
greet이 생성된 것을 볼 수 있음
function Person(name) {
this.name = name
}
Person.prototype.greet = function greet() {
return `Hi, ${this.name}!`
}
function Student(name) {
this.__proto__.constructor(name)
}
Student.prototype.study = function study() {
return `${this.name} is studying.`
}
// Studnet의 protoype 객체의 프로토타입 다시 한번 설정!
Object.setPrototypeOf(Student.prototype, Person.prototype)
const me = new Student('sunny')
console.log(me.greet())
console.log(me.study())
❗ 어떤 것으로부터 만들어졌는지 알 수 있다 ❗
console.log(me instanceof Student)
console.log(me instanceof Person)
👉 둘 다 true!!
me는 Student의 prototype을 거쳤으니깐 true
me는 Person의 prototype을 거쳤으니깐 true
class Person {
constructor(name) {
this.name = name
}
greet() {
return `Hi, ${this.name}.`
}
}
class Student extends Person {
constructor(name) {
super(name)
}
study() {
return `${this.name} is studying.`
}
}
const me = new Student('Sunny')
console.log(me.study())
console.log(me.greet())