Class와 Object
Class
Object
Class declaration
class Person {
//constructor
constructor (name, age) {
//fields
this.name = name;
this.age = age;
}
//method
speak() {
console.log(`${this.name} : hello!`);
}
}
const gyus = new Person('gyus',20);
console.log(gyus.age);
gyus.speak();
- class는 자바스크립트에서도 객체지향 코딩을 가능케 해준다.
Getter and setters
How to
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age; // age가 아닌 _age인 이유는 무한콜백때문.
}
set age(value) {
if (value < 0) {
throw Error('age can not be negative');
}
this._age = value;
//this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Gyus','Jog', -1);
- get ,set 으로 validation을 할수도 있다.