javascript class, prototype

Matthew Woo·2022년 1월 11일
0

Javascript

목록 보기
2/3
post-thumbnail

Class

class : object 를 뽑아내는 틀, 기계라고 할 수 있다.

매번 강의와 관련된 object를 생성한다고 해보자

	let lecturePython = {
      subject: '파이썬',
      instructor: '누구누구',
      rate: '10',
      reviewCount: '0'
    }
    
    let lectureEnglish = {
      subject: '영어',
      instructor: '누구누구',
      rate: '7',
      reviewCount: '0'
    }

이렇게 object들을 매번 다 작성하기보다
class를 이용해서 작성할 수 있다.


function lecture(){ // 이렇게 선언
	this.subject = '과목'
    this.instructor = '강사'
    this.rate = '평점'
    this.reviewCount = '리뷰수'
}

let lecturePython = new lecture();
let lectureEnglish = new lecture();

생성되는 class의 값들을 string으로 고정해놨지만 함수 인자로 전달하면 매번 object를 선언하면서 변수만 넣어주면 object를 수월하게 생성할 수 있다.
여기서 this는 class로 생성되는 object(instance) 이다.


function lecture(title, name, rate, cnt){ // 이렇게 선언
	this.subject = title;
    this.instructor = name;
    this.rate = rate;
    this.reviewCount = cnt;
}

class lecture2{ // 이렇게 쓸 수도 있음, 문법차이
	constructor(title, name, rate, cnt){
    	this.subject = title;
        this.instructor = name;
      	this.rate = rate;
      	this.reviewCount = cnt;
    }
}

let lecturePython = new lecture('python', 'jerry', '9', '0');
let lectureEnglish = new lecture2('english', 'Jim', '7', '0');

class는 원래 자바스크립트에서 지원하지 않는 문법이었는데 추가되어 자바스크립트도 class를 이용할 수 있다. class를 쓰게 되면 class가 object를 생성할 때 constructor함수가 실행된다.

Constructor
The constructor method is a special method of a class for creating and initializing an object instance of that class. - mdn

클래스간 중복되거나 종속되는 속성들은 부모자식 관계로 설정할 수 있다.

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

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

이미지출처

쉽게 이해를 해보았으니,
mdn이나 이제 좀 딱딱한 공식사이트에서는 뭐라고 정의하는지 살펴보자.

Classes
- mdn

Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.

클래스는 object를 생성하는 템플릿. 사용하고자 하는 데이터를 encapsulate한 것!
prototype으로 만들어졌다는데 prototype은 무엇일까?

prototype

위 예시에서 생성된 클래스를 console 찍어보면,

넣어주지도 않은 prototype이라는 것이 생성된 것을 볼 수 있다.

prototype 은 해당 객체의 원형이다. 유전자와 같은 것 이다.


이미지출처

object instance를 생성할 때 보통 빈 object를 생성하는 것이 아닌 미리 부모에게 저장되어 있는 data를 상속 받게 된다.
prototype은 class를 선언, 즉 틀을 만들면서 그 틀의 원형이 되는 것을 상속하는 원형의 object를 가리킨다.

class(틀)에서 생성된 instance들은 __proto__ 속성으로 prototype에 접근하게 된다. instance의 특정 값을 요청하였으나 해당 속성을 갖고 있지 않은경우 __proto__ 로 부모 prototype에 접근하게 되고 그래도 값이 없는 경우 그 부모의 부모 prototype에 접근하고 최상위까지 이어진 chain을 따라가서도 값이 없으면 undefined을 return한다.

아래이미지출처

prototype 코드 예시

class lecture2{ 
	constructor(title, name, rate, cnt){
    	this.subject = title;
        this.instructor = name;
      	this.rate = rate;
      	this.reviewCount = cnt;
    }
}

lecture2.prototype.admin = 'swjungle'

let lectureEnglish = new lecture2('english', 'Jim', '7', '0');

위 코드로 실행해보면,

prototype으로 넣어준 속성은 직접적으로 속성이 나타나진 않지만 그 부모 class의 부모가 해당 속성을 갖고, 자식이 해당 속성을 사용할 때는 부모로 설정된 것을 찾는다. 해당 부모도 없다면 그 부모의 부모를 찾아간다.

우리가 array.sort, .length 와 같은 것들을 쓰는 것도 해당 prototype chian 중에 array object 속성으로 sort와 length의 기능들이 추가되어 있기 때문이다.

super

super 참고

The super keyword is used to access and call functions on an object's parent.
Syntax
super([arguments]); // calls the parent constructor.
super.functionOnParent([arguments]); - mdn

super는 부모 object의 함수를 call할 수 있게 한다.

super 를 사용하면 해당 class의 부모 속성이 갖고 있는 함수를 사용할 수 있다.

참고로 부모 함수에 접근하면서 인자와 함께 이용할 수 있다.

class Cat { // 부모는 cat
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Lion extends Cat { // 자식
  speak() {
    super.speak(); // 부모의 speak함수를 가져옴
    console.log(`${this.name} roars.`);
  }
}

let l = new Lion('Fuzzy');
l.speak();
// 실행결과
// Fuzzy makes a noise.
// Fuzzy roars.
  • 자바스크립트에선 함수도 하나의 object이다.

reference

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object-oriented_JS

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

https://medium.com/@bluesh55/javascript-prototype-%EC%9D%B4%ED%95%B4%ED%95%98%EA%B8%B0-f8e67c286b67

https://www.youtube.com/watch?v=yXnbvyl04V4

profile
Code Everyday

0개의 댓글