클래스 함수 생성자와 ES6 classes 에 대해서

자바스크립트에서 클래스를 생성하는 두가지 방법

1.함수생성자

  • function을 이용한 ES6이전의 방식

  • function의 첫글자는 대문자로 시작하는게 좋음

  • new라는 키워드로 호출한다

  • 메서드를 사용할때 prototype을 사용하는 경우가 많다 (효율성)
    예를들면 prototype은 Person의 조상(원형)이기 때문에 new로 만든 모든 객체들은 해당 메서드를 공유하므로 한번만 생성된다
    그러나 함수생성자안에 넣을 경우 new로 객체를 만들때마다 해당 메서드가 생성되기때문에 불필요한 메모리 낭비가 발생함

// 일반적 사용
function Person(name) {
    this.name = name;
}

Person.prototype.hi = function () {
    console.log('hi my name is' + this.name)
}
const hannah = new Person('Hannah Yoo') 
const jisoo = new Person('Jisoo Han')

hannah.hi(); // hi my name is Hannah Yoo
jisoo.hi(); // hi my name is Jisoo Han
// 상속
function Animal(){}
Animal.prototype.eat = function () {
    console.log('eating')
}
function Cat(){}
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
Cat.prototype.meow = function () {
    console.log('meowing');
}
new Cat().meow(); // meowing
new Cat().eat(); //eating


2.클래스

  • ES6의 방식이며 이전의 함수생성자 방식을 개선함

// 일반적 사용
class Person {
    constructor(name) {
        this.name = name;
    }
    hi() {
        console.log('hi my name is ' + this.name)
    }
}
new Person('Yoon').hi(); // hi my name is Yoon
// 상속
class Animal {
    constructor(name) {
        this.name = name;
    }
    eat() {
        console.log(this.name+' is eating')
    }
}

class Cat extends Animal {
    constructor(name) {
        super(name); //name을 부모 객체의 constructor에 전달
        this.catName = name;
    }
    meow() {
        console.log(this.catName+' is meowing')
    }
}
let myCat = new Cat('냥냥이');
myCat.eat(); // 냥냥이 is eating
myCat.meow(); // 냥냥이 is meowing

※참조

https://uiyoji-journal.tistory.com/101

https://www.zerocho.com/category/JavaScript/post/573c2acf91575c17008ad2fc

Jan 13, 2023 Views 113