Class
클래스 사용 예제 입니다
class User {
// 생성자 : 생성자는 클래스 안에서 반드시 constructor 라는 이름으로 정의 한다
constructor({name,age}){
this.name = name;
this.age = age;
}
// 메소드를 만드는문법 그대로 사용하면 메소드가 자동으로 User.prototype 에 저장된다
msg() {
return '안녕하세요. 제이름은 '+this.name+'입니다';
}
}
const obj = new User({name:'호호호',age:20});
console.log(obj.msg());
console.log(typeof User);//function
console.log(typeof User.prototype.constructor);//function
console.log(typeof User.prototype.msg);//function
console.log(obj instanceof User);// true
class User{
add(x,y){
return x+y;
}
subtract(x,y){
return x-y;
}
}
const obj = new User();
console.log(obj.add(10,5));//15
console.log(obj.subtract(8,5));//3
const mathodName = 'sayName';
class User{
constructor(name,age){
this.name = name;
this.age = age;
}
// 임의의 표현식을 []로 둘러쌓아 메소드 이름으로 사용
[mathodName](){
return `안녕 나는 ${this.name}이야`;
}
}
const obj = new User('나나나',10);
console.log(obj.sayName());