ES5 자바스크립트에서 Class는 어떻게 동작할까요?

Calvin Park·2022년 8월 11일
0

QClass는 대체로 추상화를 위해 사용됩니다. 그러면 ES5 vs ES6의 차이점에 class 차이점에서 알아보자.

ES5는 class라는 키워드가 없다. 그러면 어떻게 클래스 수준의 기능을 구현을 할까?

답은 간단하다. functions.를 사용하면 된다.
현재 this 라는 키워드는 아주 간단하게 쉽게 속성을 추가할 수 있게되었다.
자바스크립트 개발자들은 prototype이라는 키워드가 있는지도 모르고 어떻게 사용을 하는지도 모른는 개발자들이 많다고 한다.
일단 간단하게 예시를 들어 보면 이렇다

// 1. JSON objects in javascript and if we want to the list of all the keys of that object ,we can use object.keys(someObj)
const user = {
   id: 1,
   name: "calvin park",
   email: "Calvinpark@gmail.com",
   isActive: true,
};
//['id', 'name', 'email', 'isActive']

하지만 자바스크립트에서는 someObj.key()를 사용해도 모든 key의 목록을 얻을 수 없다.
저 위에 있는 코드를 예시를 들어보자

console.log(typeof user)
//object
//그리고 properties 확인이 가능하게
console.log(Object.prototype)

여기서 기능을 추가해 보자, this라는 키워드를 사용하여 해당 함수를 호출하는 객체의 키 배열을 반환한다.

const user = {
  id: 1,
  name: "Calvin Park",
  isActive: true,
};

Object.prototype.keys = function () {
  return Object.keys(this);
};

console.log(user.keys());

자바스크립트에서는 이렇게 어디든지 사용이 가능하다. 일부 기능을 추가하고 문자열로 함께 사용할려면 String.prototype.someFeature = your logic.

본론으로 돌아가서 ES6 Class는 어떻게 생긴것인가?

ES6몇가지 간단한 단계를 통해 코드의 가독성을 해치지 않고 쉽게 모든 기능을 구현할 수 있는지 예시를 통해 알아보자!
person class는 3가지 속성을 가지고 있다. name, age, gender
그리고 Teacher 와 Studnet가 다른 class 그리고 이 class 는 person을 extend한다. teacher는 subject를 student는 mark를 가지고 있다.

'use strict';

/**
 * Person class.
 *
 * @constructor
 * @param {String} name - name of a person.
 * @param {Number} age  - age of a person.
 * @param {String} gender  - gender of a person.
 */

class Person {
  constructor(name, age, gender) {
    this.name = name;
    this.age = age;
    this.gender = gender;
  }

  getName() {
    return this.name;
  }

  getAge() {
    return this.age;
  }

  getGender() {
    return this.gender;
  }
}

/**
 * Teacher class.
 *
 * @constructor
 * @param {String} name - name of a teacher.
 * @param {Number} age  - age of a teacher.
 * @param {String} gender  - gender of a teacher.
 * @param {String} subject - subject of a teacher.
 */

class Teacher extends Person {
  constructor(name, age, gender, subject) {
    super(name, age, gender);

    this.subject = subject;
  }

  getSubject() {
    return this.subject;
  }
}

/**
 * Student class.
 *
 * @constructor
 * @param {String} name - name of a student.
 * @param {Number} age  - age of a student.
 * @param {String} gender  - gender of a student.
 * @param {Number} marks - marks of a student.
 */

class Student extends Person {
  constructor(name, age, gender, marks) {
    super(name, age, gender);
    this.marks = marks;
  }

  getMarks() {
    return this.marks;
  }
}

const teacher = new Teacher('John Doe', 30, 'male', 'Maths');
const student = new Student('Jane Miles', 12, 'female', 88);

console.log(
  'Teacher:',
  teacher.getName(),
  teacher.getAge(),
  teacher.getGender(),
  teacher.getSubject(),
);
console.log(
  'Student:',
  student.getName(),
  student.getAge(),
  student.getGender(),
  student.getMarks(),
);

이 예에서 보는거와 같이, 인수를 전달하고 있는 클래스는 생성자를사용하여 이러한 인수를 처리하고 있다. 그리고 독립적인 값을 가지도록 "this"를 바인딩 하고 있다.

extends를 사용하여서 하위 클래스에 자동으로 할당되도록 했다. 또한 모든 클래스의 모든 속성이 함께 범위가 지정이 되어서 코드가 짤끔하고 가독성이 항상된다.super를 사용을해서 기본 클래스의 생성자를 호출 할 수 있다.

class ES5

ES5 에서는 어떻게 구동이 되는지 알아보자.
일단 프로토타입을 사용하여 새 속성을 추가/확장할 수 있고, 기능에서도 동일한 작업을 수행한다. 함수는 인수를 사용하고 매개변수를 "this"로 바인딩한다.

'use strict';

/**
 * Person class.
 *
 * @constructor
 * @param {String} name - name of a person.
 * @param {Number} age  - age of a person.
 * @param {String} gender  - gender of a person.
 */

function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}

Person.prototype.getName = function() {
  return this.name;
};

Person.prototype.getAge = function() {
  return this.age;
};

Person.prototype.getGender = function() {
  return this.gender;
};

/**
 * Teacher class.
 *
 * @constructor
 * @param {String} name - name of a teacher.
 * @param {Number} age  - age of a teacher.
 * @param {String} gender  - gender of a teacher.
 * @param {String} subject - subject of a teacher.
 */

function Teacher(name, age, gender, subject) {
  Person.call(this, name, age, gender);
  this.subject = subject;
}

Teacher.prototype = Object.create(Person.prototype);

Teacher.prototype.getSubject = function() {
  return this.subject;
};

/**
 * Student class.
 *
 * @constructor
 * @param {String} name - name of a student.
 * @param {Number} age  - age of a student.
 * @param {String} gender  - gender of a student.
 * @param {Number} marks - marks of a student.
 */

function Student(name, age, gender, marks) {
  Person.call(this, name, age, gender);
  this.marks = marks;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.getMarks = function() {
  return this.marks;
};

const teacher = new Teacher('John Doe', 30, 'male', 'Maths');
const student = new Student('Jane Miles', 12, 'female', 88);

console.log(
  'Teacher:',
  teacher.getName(),
  teacher.getAge(),
  teacher.getGender(),
  teacher.getSubject(),
);
console.log(
  'Student:',
  student.getName(),
  student.getAge(),
  student.getGender(),
  student.getMarks(),
);

ES5 에서는 객체에 새로운 속성을 추가하고 싶을 때마다 프로토타입을 사용해야 한다. ES5에서는 모든 속성을 확장 기능이 없고, 초기화용 생성자 또는 기본 클래스의 생성자를 호출할 수 있는 super도 없다...

출처

profile
Personal Velog Note

0개의 댓글