본문 바로가기

#IT 글로써

JavaScript - "is a" and "has a"

"is a" - 상속 (Inheritance)

is-a는 클래스들 사이의 포함 관계를 의미한다. 즉, 한 클래스가 다른 클래스의 서브클래스임을 말한다.

var Coffee = function () {
  this.shots = 2;
};

var Latte = function (water) {
  this.water = water;
};

Latte.prototype = new Coffee();  // set Coffee as 'ancestor' object

var latte = new Latte('milk');

console.log(latte.water);  // => milk
console.log(latte.shots);  // => 2

console.log(latte instanceof Latte);  // => true
console.log(latte instanceof Coffee);  // => true
console.log(latte instanceof Object);  // => true

 

"has a" - 객체합성 (Object Composition)

has-a는 한 오브젝트가 다른 오브젝트에 속하는 관계를 말한다.

var Machine = function () {
  this.name = 'Starbucks Machine';
};

var Latte = function () {
  this.machine = new Machine();
};

var starbucks = new Latte();
console.log(starbucks.machine.name);	// => Starbucks Machine