티스토리 뷰

728x90
반응형

함수 타입 선언의 this 바인딩 메소드들 : call, apply, bind

 

1. call() : 함수안에 사용되는 this의 값을 지정해 줄 수 있다.

function showName() {
	console.log(this.name);
}
showName(); // 이 때 this는 window를 바라보고 있다.

→ 여기서 showName함수를 호출할 때 call을 써서 this를 원하는 값으로 지정해보자

const green = {
    name: "green",
    age: 26
}
const blue = {
    name: "blue",
    age: 30
}
function showName() {
    console.log(this.name);
}
showName.call(green); // 이 때 this는 green객체가 된다.
showName.call(blue); // 이 때 this는 blue객체가 된다.

 

 

2. apply() : 함수의 매개변수를 처리하는 방법을 제외하면 call메소드와 동일함

 

 call메소드와 apply메소드의 매개변수를 처리하는 방법 차이

- call : 일반적인 함수와 같이 매개변수를 받음

 // 매개변수를 가지는 함수 작성
function update(birth, job) {
    this.birth = birth;
    this.job = job;
}
// this의 값을 위의 객체로 지정해서 값을 업데이트 해보자 
update.call(green, 1996, "teacher");
update.call(blue, 1994, "dortor");

- apply : 매개변수를 배열로 받음

// this의 값을 위의 객체로 지정해서 값을 업데이트 해보자 
update.apply(green, [1996, "teacher"]);
update.apply(blue, [1994, "dortor"]);

 

 

3. bind() : 함수에서 사용할 this를 영구적으로 지정한다.

- 구문 : const 변수 = 함수.bind(this대상객체);

- 호출 : 변수()

 


 

클래스 타입 선언의 종류

 

1. 접근 제한자

 

접근 제한자 키워드 : public, protected, private

 

  • 사용 범위 = 필드 & 메소드
  • 클래스를 사용해 만들어진 객체 = 인스턴스

 

1) public : 어디서나 자유롭게 접근할 수 있음(키워드 생략 가능)

내 클래스 내부, 인스턴스, 자식 클래스에서도 접근할 수 있다.

 

2) protected : 내 클래스 내부, 자식 클래스에서 접근 가능 (인스턴스 X)

 

3) private : 내 클래스 내부에서만 접근할 수 있다 (인스턴스, 자식 클래스 X)

 

예제 >

 

- public일 때

class ClassAnimal {
    public name: string;
    constructor(name: string) {
        this.name = name;
    }
}
class ClassCat extends ClassAnimal {
    public getName(): string {
        return `Cat name is ${this.name}`;
    }
}
let cat = new ClassCat('레오');
cat.name = '까미';
cat.getName();
// 에러가 아무 곳에도 뜨지 않는다 !

 

 

- protected일 때 

class ClassAnimal {
    protected name: string;
    constructor(name: string) {
        this.name = name;
    }
}
class ClassCat extends ClassAnimal {
    protected getName(): string {
        return `Cat name is ${this.name}`;
    }
    public sound(): void {
        console.log('야옹');
    }
}
let cat = new ClassCat('레오');
cat.name = '까미'; // 인스턴스로 접근할 수 없기 때문에 에러가 뜬다..
console.log(cat.getName()); // 인스턴스로 접근할 수 없기 때문에 에러가 뜬다..
cat.sound(); // 이 친구는 public으로 정의 되어있어서 에러가 뜨지 않는다 !

 

- private일 때 

class ClassAnimal {
    private name: string;
    constructor(name: string) {
        this.name = name;
    }
}
class ClassCat extends ClassAnimal {
    public getName(): string {
        return `Cat name is ${this.name}`; // 자식 클래스에서도 접근할 수 없기 때문에 에러...
    }
    private sound(): void {
        console.log('야옹');
    }
}
let cat = new ClassCat('레오');
console.log(cat.getName()); // public으로 지정했기 때문에 에러 뜨지 않음 !
cat.sound(); // 인스턴스로 접근할 수 없으므로 에러...
cat.name = '까미'; // 인스턴스로 접근할 수 없으므로 에러..

 


 

 

2. 정적 멤버 & 인스턴스 멤버

 

- 사용 범위 => 필드 & 메소드

 

1) 정적 멤버 : 클래스가 가지는 멤버 this나 인스턴스로 접근할 수 없음

 

2) 인스턴스 멤버 : 클래스로 만들어진 인스턴스(객체)가 가지는 멤버

class ClassAnimal {
    name: string;
    // 정적 멤버 변수 선언 (클래스명.변수명)
    // 이 친구는 this나 인스턴스로 접근할 수 없음 ! 
    static eye = 2;
    constructor(name: string) {
        this.name = name;
    }
    // 정적 멤버 메소드 정의 (클래스명.메소드명)
    // 인스턴스로 접근할 수 없음! 
    static eat(): void {
        console.log('냐미');
    }
}
class ClassCat extends ClassAnimal {
    getName(): string {
        return `Cat name is ${this.name}`;
    }
}
let cat = new ClassCat('레오');
// console.log(cat.eye); => 에러
// console.log(cat.eat()); => 에러 
console.log(ClassAnimal.eye); // good
console.log(ClassCat.eye); // 자식 클래스에도 접근 가능 ! 

// cat.eat(); => 에러
ClassAnimal.eat(); // good

 

 


 

 

추상 클래스 / 추상 메소드

 

키워드 : abstract

 

추상 클래스 : 상속만 가능, 인스턴스(객체) 생성 불가능

오직 상속만을 위한, 부모 클래스로서의 기능만을 할 수 있다.

 

추상 메소드 : 선언부만 있고, 구현부는 상속받는 쪽에서 함

상속받는 자식 클래스는 모두 다 같은 이름의 메소드를 가지며 구현은 각각 다르게 할 수 있다.

 

예제 >

abstract class Person {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    // 추상 메소드 정의
    // 이 친구는 선언하면 반드시 자식 클래스에 구현을 해야 한다
    abstract work(): void; 
}
class Teacher extends Person {
    work(): void {
        console.log('가르키는 직업입니다.');
        
    }
}
class Engineer extends Person {
    work(): void {
        console.log('자동차 정비하는 직업입니다.');
        
    }
}
let person1 = new Person('anna'); // 에러 (추상 클래스는 인스턴스를 만들 수 없다 !)
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함