CLASS

이남수·2020년 2월 7일
0

상속

function Person(name, age){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
}

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


function Employee(name, age, position){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
  this.position = position || '직책모름'
}

Employee.prototype.getName = function() { 
  return this.name;
}
Employee.prototype.getPosition = function() {
  return this.position;
}

중복된 메소드와 프로퍼티를 줄이기 위해 상속을 사용

function Person(name, age){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
}

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

function Employee(name, age, position){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
  this.position = position || '직책모름'
}

Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.getPosition = function() { 
  return this.position;
}

person의 getName메소드는 잘가져오지만 불필요한 person의 static property를 가져온다.

해결하기위해 bridge를 만들어서 person의 prototype 메소드만 가져온다.

function Person(name, age){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
}

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

function Employee(name, age, position){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
  this.position = position || '직책모름'
}

function Bridge(){}
Bridge.prototype = Person.prototype;
Employee.prototype = new Bridge();
Employee.prototype.constructor = Employee;
Employee.prototype.getPosition = function() { 
  return this.position;
}

깔끔하게 정리한 extend 메소드

var extendClass = (fucntion(){
	function Bridge(){}
	return function(Parent, Child){
      Bridge.prototype = Parent.prototype;
      Child.prototype = new Bridge();
      Child.prototype.constructor = Child;
      Child.prototype.superClass = Parent;
    }
})();	//bridge 는 실제 사용하는것이 아닌 중간다리 역활이므로 클로져를 이용하여 사용
function Person(name, age){
  this.name = name || '이름없음';
  this.age = age || '나이모름';
}
Person.prototype.getName = function() { 
  return this.name;
}
function Employee(name, age, position){
  this.superClass(name, age);
  this.position = position || '직책모름';
}
extendClass(Person, Employee);
Employee.prototype.getPosition = function() { 
  return this.position;
}

es6에서는 class가 나와서 더 쉽게 상속을 구현할수 있다.

class Person {
  constructor (name, age) {
    this.name = name || '이름없음';
  	this.age = age || '나이모름';
  }
  getName () { 
    return this.name;
  }
}
class Employee extends Person {
  constructor (name, age, position) {
    super(name, age);
    this.position = position || '직책모름';
  }
  getPosition () { 
    return this.position;
  }
}
  
profile
큘슈호윤

0개의 댓글