JS 클래스

숩인·2023년 11월 24일
0

Javascript

목록 보기
6/9

1. 생성자 함수(prototype)

  • 생성자는 객체를 만드는 역할을 하는 함수
  • 함수에 new 를 붙이면 그 리턴 값은 객체가 된다
  • 함수의 이름의 첫 글자는 대문자로 시작

객체 리터럴 사용 객체 만들기

let user = {
  name : 'park;,
  age : 24,

단일 객체를 만들 때는 리터럴 방식을 사용해 user라는 객체를 생성,
값만 다른 여러 개의 객체가 필요할 때 일일이 객체를 만들어 줄 필요 없이 생성자 함수를 만들어 주면 됨

this를 이용한 생성자 함수 만들기

function User(name, age) { 
  //생성자 함수는 보통 첫글자를 대문자로 함.
    this.name=name;
    this.name=age;
}

const user1 = new User('park',24); 

틀을 만들어 준 후 new 를 사용하여 함수의 인스턴스를 생성하게 되면 this로 생성된 객체를 참조

개체 프로토타입

function User(first, last) {
    this.firstName = first;
    this.lastName = last;
}
User.prototype.getFullName = function () {
    return `${this.firstName} ${this.lastName}`;
};

const heropy = new User("Heropy", "Park");
const amy = new User("Amy", "Clarke");
const neo = new User("Neo", "Smith");

console.log(heropy.getFullName());
console.log(amy);
console.log(neo);

생성자를 사용하여 여러개의 객체를 생성하고
프로토타입을 사용하여 속성과 메서드를 생성자에 추가할 수 있다.

2. This

  • 일반함수는 호출위치에 따라 this를 정의
  • 화살표 함수는 자신이 선언된 함수 범위에서 this를 정의
    (콜백에서는 화살표함수를 사용하면 유용함 / 특정한 범위내에서 함수가 정의되기 때문)
const heropy = {
    name: "Heropy",
    normal: function () {
        console.log(this.name);
    },
    arrow: () => {
        console.log(this.name);
    },
};

heropy.normal();
heropy.arrow();
>Heropy
>undefined

const amy = {
    name: "Amy",
    normal: heropy.normal,
    arrow: heropy.arrow,
};

amy.normal();
amy.arrow();
>amy
>undefined

화살표함수 사용 시 undefined 가 나오는 이유는 선언된 범위 안에 아무것도 정의가 되어있지 않기 때문

const timer = {
    name: "Heropy!!",
    timeout: function () {
        setTimeout(() => {
            console.log(this.name);
        }, 2000);
    },
};

timer.timeout();

콜백함수 내 범위 안에 선언이 되어있기 때문에 "Heropy" 출력

3. ES6 Classes

constructor() 생성자함수로 속성설정

class User {
    constructor(first, last) {
        this.firstName = first;
        this.lastName = last;
    }
    getFullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}

const heropy = new User("Heropy", "Park");
const amy = new User("Amy", "Clarke");
const neo = new User("Neo", "Smith");

console.log(heropy);
console.log(amy.getFullName());
console.log(neo.getFullName());

생성자 메서드는 function 키워드 없이 작성
이 메서드는 this 문맥을 생성하기 때문에 this 속성을 할당함

상속

  • extends를 사용하여 상속
class Vehicle {
    constructor(name, wheel) {
        this.name = name;
        this.wheel = wheel;
    }
}

const myVehicle = new Vehicle("운송수단", 2);
console.log(myVehicle);

class Bicycle extends Vehicle {
    constructor(name, wheel) {
        super(name, wheel);
    }
}

const myBicycle = new Bicycle("삼천리", 2);
const daughtersBicycle = new Bicycle("세발", 3);
console.log(daughtersBicycle);

class Car extends Vehicle {
    constructor(name, wheel, license) {
        super(name, wheel);
        this.license = license;
    }
}
const myCar = new Car("벤츠", 4, true);
const daughtersCar = new Car("포르쉐", 4, false);

console.log(myCar);
console.log(daughtersCar);

다음과 같은 결과가 나옴

profile
프론트엔드 개발자를 꿈꾸는 병아리

0개의 댓글

관련 채용 정보