• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

protected userVote: number;

22.12.22 18:37 작성 조회수 169

0

강사님 안녕하세요,

 protected userVote: number;

  setUserVote(user: User){
    const index= this.votes?.findIndex(v=> v.username === user.username);
    this.userVote = index > -1 ? this.votes[index].value : 0;
  }

위의 코드에서 protected userVote: number;
이 부분을 어떻게 받아들여야할지 모르겠습니다

예전에 자바를 겉핥기로 본적이있어서 의미하는 바는 대강알겠는데
protected userVote: number; 이거를 명시해준거는

let userVote; 이렇게 혹은 const userVote; 이런식으로 명시해준것과 같은걸까요?

답변 1

답변을 작성해보세요.

1

안녕하세요!

넵 그렇게 생각해주시면 됩니다.
하지만 다른 점은
클래스의 접근 제한자를 이해해주셔야 하는데
여기 쓰여있는 protected 같은 경우는

class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}
class Employee extends Person {
    private department: string;
    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }
    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}
let howard = new Employee("John Smith", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error

 

Person 클래스의 외부에서 protected name 이라고 해준 name을 사용할 수는 없습니다.
사용하려고 하면
let han = new Person("Han"); // Error: The 'Person' constructor is protected
이런 식의 에러를 내보냅니다.
그 대신 Employee 클래스가 Person 부모 클래스를 확장해서 사용하고 있기에
protected 된 name 을 Employee 클래스 안에 있는 메소드에서는 사용할 수 있습니다.
그래서
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());

이 부분은 가능하게 되는 것입니다!
이 부분에 관해서는
typescript 접근 제한자를 구글링 하시면 더 많은 정보를 얻을 수 있을 거 같습니다!
https://infoscis.github.io/2017/05/20/TypeScript-handbook-classes/
여기에 되게 잘 나와있네요 !!

감사합니다!