본문 바로가기
깃허브 링크!
javascript

클래스의 생성자 함수와 static함수

class Mother{
    constructor(name, age){// 생성자 함수
            this.name = name;
            this.age = age;
}
getInfo(){
    return console.log(`이름은 : ${this.name} 나이는 : ${this.age} 입니다.}`)
    }
}

let temp = new Mother("아무개" , 30);
temp.getInfo();

// 클래스의 상속 자식 클래스가 부모클래스를 상속받아서 부모클래스의 기능을
// 사용할수있다.
// 클래스를 사용하는 이유
// extend 키워드를 사용해서 클래스를 상속 시킬수 있다.

// 부모 클래스의 기능을 상속 받아서 사용 할수있다.
class Child extends Mother{
    // 비워놓자
    // 비워놓으면 자동으로 생성자가 만들어진다 했음
    // constructor 자동으로 생성된다.
}

this를 사용해주는 이유는 해당 객체를 나타내기 위함이다.

class 생성자 함수를 사용하면 부모 클래스의 기능을 상속 받아서 사용할수 있어서 간편한점이 있다.

 

 

class Product{
    constructor(name, price){ // 생성자 함수 만들고 시작하자.
        this.name = name;
        this.price = price;
    }
    // getter setter
    // get : 값을 호출할때 네이밍
    // set : 값을 수정할때 네이밍 
    // 클래스의 값을 가져오거나 설정할때 getter와 setter를 제공해준다.
    // 클래스의 값에 접근할때 직접 변수에 접근하는 형태가 아닌 get과 
    // set을 통한 접근방법
    // 내부구조를 캡슐화 하는데 좋다.
    // 전역적으로 데이터가 사용되지 않게 위험성을 방지해준다.
    // 객체지향

    get getName(){
        return "제품이름 : "+this.name;
    }

    set setPrice(price){
        this.price = price;
    }
}

let pr = new Product("갤럭시 노트" , 1000000);
console.log(pr);
 // getter를 확인해보자
console.log(pr.getName);
// setter를 사용해보자
pr.setPrice = 2000;
console.log(pr);

new product가 객체를 생성해주는데 

객체의 정의:{key: value , key: value2 ....} 키와 값이 묶인 형태이다.

키:name,price

값:갤럭시노트,10000

 

 

// Class Es6 부터 지원했고
// Class를 사용하면 상속을 지원한다.
// 코드의 재사용을 더 높일수있다.

function aa(){
    this.name = name;
}

// 클래스의 생성자 함수
class student {
    // 클래스의 생성자 함수 constructor있다.
    // constructor() 생성자함수를 작성안하면  constructor()
    // 빈 생성자 함수가 자동으로 생긴다.
    constructor(age,phone,city){
        this.age = age;
        this.phone = phone;
        this.city = city;
    }
    getInfo(){
        return "나이는 : " + this.age + "살인 핸드폰 번호는" +this.phone +
         "사는곳 : "+ this.city + "임"
    }
}

let st = new student(30,30,"서울");
console.log(st);
console.log(st.age);
console.log(st.getInfo());

class Character{
    constructor(hp, mp, atk){
        this.hp = hp;
        this.mp = mp;
        this.atk = atk;

    }
    getState(){
        return this.hp + this.mp + this.atk;
    }
    // 정적 메소드 : 일반적으로 공용함수를 만들기위해 사용.
    // 클래스의 인스턴스에서 호출 X 
    // static 메소드는 클래스를 동적할당 할때마다 생성 되지 않는다.
    // 한개만 있음
    // 인스턴스를 생성할때 더 생성되지 않는다.
    static getAtk(n){
        return n.atk;
    }
}

let ca = new Character(100,100,100);
console.log(ca);
// 이렇게 생성한 인스턴스에서 호출하면 안됨!
// console.log(ca.getAtk(1));
console.log(Character.getAtk(ca));

class Product{
    constructor(name, price){ // 생성자 함수 만들고 시작하자.
        this.name = name;
        this.price = price;
    }
    // getter setter
    // get : 값을 호출할때 네이밍
    // set : 값을 수정할때 네이밍 
    // 클래스의 값을 가져오거나 설정할때 getter와 setter를 제공해준다.
    // 클래스의 값에 접근할때 직접 변수에 접근하는 형태가 아닌 get과 
    // set을 통한 접근방법
    // 내부구조를 캡슐화 하는데 좋다.
    // 전역적으로 데이터가 사용되지 않게 위험성을 방지해준다.
    // 객체지향

    get getName(){
        return "제품이름 : "+this.name;
    }

    set setPrice(price){
        this.price = price;
    }
}

let pr = new Product("갤럭시 노트" , 1000000);
console.log(pr);
 // getter를 확인해보자
console.log(pr.getName);
// setter를 사용해보자
pr.setPrice = 2000;
console.log(pr);

 

 

 

 

static 정적 메소드를 사용해보자

생성자 함수를 만들때 일반함수 같은 경우에는 새로운 객체를 만들었을때 가져와 쓸수있는 반면

그렇지만 static은 가져와서 쓸수가 없다. // 클래스의 인스턴스에서 호출x

 

static은 캐릭터 생성자 함수에 고정되어있는 메소드라서 새로운 객체를 생성했을때 가져올수 없다.

그래서 가져올려면 생성자 함수 내에서 바로 가져와야 한다.

 

static --> 메모리 측면에서 효율적이다.

 

 

 

 

'javascript' 카테고리의 다른 글

야구 미니게임  (0) 2023.04.06
프로토타입,클로저,즉시 실행 함수 작성법, 이터러블  (0) 2023.04.05
자기소개 웹사이트 만들기  (0) 2023.04.03
3/13 했던 업다운  (0) 2023.03.29
자습  (0) 2023.03.28