HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🐣
프론트엔드 데브코스 4기 교육생
/
클래스를 이용하면 메모리 낭비가 사라지는 이유

클래스를 이용하면 메모리 낭비가 사라지는 이유

강의 자료
객체지향과 프로토타입
태그
JavaScript 문법 및 CS
작성인

질문

1주차 Day2의 객체지향과 프로토타입 05:09에서 해당 생성자 함수를 이용했을때 getName과 setName에 대해 메모리 낭비가 있다고 하셨는데 만약 클래스로 객체를 똑같이 진행하면 메모리 낭비가 없어지나요?
class Person { constructor(name, age) { this.name = name; this.age = age; } getName() { return this.name; } setName(name) { this.name = name; } } let A = new Person("김형욱", "25"); let B = new Person("홍길동", "15"); console.log(A); console.log(B); function Person1(name, age) { this.name = name; this.age = age; this.getName = function () { return this.name; }; this.setName = function () { this.name = name; }; } let C = new Person1("김형욱", "25"); let D = new Person1("홍길동", "15"); console.log(C); console.log(D);
해당 Person을 클래스로 만들어 A,B를 출력하면 getName과 setName은 나타나지 않고 A.__proto__  와 B.__proto__에 존재하는 것으로 확인을 해서요  C,D의 경우에는 강의내용에서 처럼 출력하면 getName과 setName이 각각 나타나 메모리낭비가 있다고 생각하고요

답변

클래스는 프로토타입 사용을 syntactic sugar으로 만든 것이기 때문에 프로토타입을 사용한 것과 동일합니다. 만약 저 클래스를 프로토타입으로 나타낸다면
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.getName = function () { return this.name; } Person.prototype.setName = function (name) { this.name = name; }
위 코드와 같습니다.