OOP- inheritance pattern

Seungjae Han·2020년 9월 22일
0

Javascript의 OOP

ES6 이전 Javascript는 prototype을 이용해 OOP를 해왔다. 사실 Java나 Python, C++과 같이 Class의 기능을 모두 사용하는 방식은 아니지만 비슷하게 OOP를 만들었다. Python과 비교해 Javascript의 OOP를 설명하는 것도 다룰 예정이다.

pseudoclassical

pseudoclassical이란 pseudo(가짜)+class(클래스)+ical(~한)으로 클래스인척 하는 이란 뜻이다. prototype의 기능을 이용해서 class의 흉내를 내보겠다.

let point = function(x,y){
  this.x = x;
  this.y = y;
}
// 길이를 나타내는 메소드가 추가됩니다.
point.prototype.line2DLength = function(){
  return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2));
}
let a = new point(1,2);
a.line2DLength();//2.23606797749979

let point3 = function(x,y,z){
  point.call(this,x,y);
  this.z = z;
}

point3.prototype = Object.create(point.prototype);
point3.prototype.constructor = point3;

point3.prototype.line3DLength = function(){
  return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2)+Math.pow(this.z,2));
}

let b= new point3(1,2,3);
b.line3DLength();//3.7416573867739413

위 과정은 2D 환경을 만들어주는 생성자의 prototype들을 3D환경에 상속시켜주는 과정이다. 상속은 OOP의 속성이며 class에서 존재하는 개념이다. 그런데 이를 비슷하게 class인척 꾸며 줄 수 있다.

같은 과정을 Class에서 해보겠다.

Class

class point{
  constructor(x,y){
    this.x = x;
    this.y = y;
  }
  line2DLength = function(){
    return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2));
  }
}

let a = new point(1,2);
a.line2DLength();//2.23606797749979

class point3 extends point{
  constuctor(x,y,z){
    super(x,y);
    this.z = z;
  }
  line3DLength = function(){
    return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2)+Math.pow(this.z,2));
  }
}

let b= new point3(1,2,3);
b.line3DLength();//3.7416573867739413

Class는 es6에서 새로 나온 기능으로 prototype언어를 기반으로 하는 javascript에서 OOP를 본격적으로 지원해주기 위해 처음으로 만든 기능이다.
위와 같은 상속과정을 통해 OOP를 만들어 낼 수 있다.

profile
공부하는 개발자 재밌게 일하고 싶습니다.

0개의 댓글