클래스와 객체의 혼합

클래스 지향 디자인패턴

I. 클래스 이론

1. 클래스 디자인 패턴

2. 자바스크립트 클래스

II. 클래스 체계

III. 클래스 상속

1. 다형성

2. 다중 상속

IV. 믹스인

1. 명시적 믹스인

function mixin(sourceObj, targetObj) {
  for (var key in sourceObj) {
    if (!key in targetObj) {
      targetObj[key] = sourceObj[key];
    }
  }
  return targetObj;
}

var Vehicle = {
  engines: 1,
  ignition: function() {
    console.log("엔진을 켠다.")
  },
  drive: function() {
    this.ignition();
    console.log("방향을 맞추고 앞으로 간다!");
  }
};

var Car = mixin(Vehicle, {
  wheels: 4,
  drive: function() {
    Vehicle.drive.call(this);
    console.log(this.wheels + "개의 바퀴로 굴러간다!");
  }
});

다형성 재고

2. 암시적 믹스인

var Something = {
  cool: function() {
    this.greeting = "Hello World";
    this.count = this.count ? this.count + 1 : 1;
  }
};

Something.cool();
Something.greeting();
Something.count();

var Another = {
  cool: function() {
    Something.cool.call(this);
  }
};

Another.cool();
Another.greeting();
Another.count;