자바로 작성한 class Person이다.
class Person {
private String name;
private int age;
void setName(String name) {
this.name = name;
}
void setAge(int age) {
this.age = age;
}
String getName() {
return this.name;
}
int getAge() {
return this.age;
}
}
public class Main {
public static void main(String[] args) {
Person p1 = new Person();
p1.setName("sjh");
p1.setAge(112);
System.out.println(p1.getName());
System.out.println(p1.getAge());
}
}
자바스크립트로 작성한 class Perosn 이다. 여기서 자바스크립트에 getter setter를 설정
해주었다. 자바스크립트로 getter와 setter를 설정할 때에는 주의해야한다.
예를 들어 변수 age 부문과 관련해서 getter와 setter를 만들었다고 하자. 그러면 this.age
= age; 라는 생성자 코드블록 안에 있는 코드의 this.age는 getter를 호출하고 age는 setter
를 호출한다.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
get age() {
return this._name;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
speak() {
console.log(`${this.name}: hello`);
}
}
const p1 = new Person('sjh', 112);
console.log(p1.name, p1.age);
p1.speak();