javascript
//javascript
class Person {
constructor(name, age){
console.log('생성 되었습니다.');
this.name = name;
this.age = age;
}
}
let profile = new Person('olive',26);
typescript
class Person {
name:string;
age:number;
constructor(name:string,age:number){
console.log('생성 되었습니다.');
this.name = name;
this.age = age
}
}
prototype?
class Person {
private name:string;
public age:number;
constructor(name:string,age:number){
// ...
}
}
private
: 해당 클래스 안에서만 사용할수 있다.public
: 클래스 밖에서도 사용할수 있다.클래스에서 접근은 가능하지만 값이 변하지 않게 하고 싶을경우에는readonly
를 사용
// typescript
class Developer {
readonly name: string;
constructor(theName: string){
this.name = theName;
}
}
let olive = new Developer('olive');
olive.name = '0live" // error! name is readonly
이처럼 readonly를 사용하면 constructor() 함수에 초기 값 설정 로직을 넣어줘야 하므로 인자에 readonly 키워드를 추가해서 코드를 줄일 수 있습니다.
class Developer {
readonly name: string;
constructor(readonly name: string) {
}
}