클래스에서 속성 부여하는 방법
1. 생성자(constructor) 내부
2. class 내부
3. class 외부
class obj1 {
constructor(){
this.name = 'kim';
this.age = '20'
}
class obj1 {
constructor(name, age){
this.name = 'kim';
this.age = '20'
}
문법
class obj1 {
constructor(name, age){
this.name = name;
this.age = age
this.sayHi2 = ()=>{
console.log('안녕2'+this.name)
}
}
}
특징
부여된 속성은 인스턴스가 직접 소유하게 된다.
문법
class obj1 {
constructor(name, age){
this.name = name;
this.age = age
}
sayHi(){
console.log('안녕 ' + this.name)
}
특징
부여된 속성은 인스턴스가 참조하여 사용한다.(인스턴스가 해당 메소드를 가지진 못함)
수정 시 용이하다.
문법
class obj1 {
constructor(name, age){
this.name = name;
this.age = age
}
obj1.prototype.sayHi3 = function(){
console.log('안녕3 나는' + this.name)
}
주의할 점
클래스 외부에서 메소드 부여할 때 && this 사용 시 arrow function 사용 X
(this를 생성자가 아닌 window객체로 인식하므로)