原型模式

原型模式側重於建立一個物件,該物件可以通過原型繼承用作其他物件的藍圖。由於 JS 中對原型繼承的原生支援,這種模式本身很容易在 JavaScript 中使用,這意味著我們不需要花時間或精力模仿這種拓撲。

在原型上建立方法

function Welcome(name) {
  this.name = name;
}
Welcome.prototype.sayHello = function() {
  return 'Hello, ' + this.name + '!';
}

var welcome = new Welcome('John');

welcome.sayHello();
// => Hello, John!

原型繼承

通過以下模式從父物件繼承相對容易

ChildObject.prototype = Object.create(ParentObject.prototype);
ChildObject.prototype.constructor = ChildObject;

其中 ParentObject 是你希望繼承原型函式的物件,而 ChildObject 是你希望將它們放在上面的新物件。

如果父物件具有在其建構函式中初始化的值,則在初始化子物件時需要呼叫父建構函式。

你可以在 ChildObject 建構函式中使用以下模式執行此操作。

function ChildObject(value) {
    ParentObject.call(this, value);
}

完成上述操作的完整示例

function RoomService(name, order) {
  // this.name will be set and made available on the scope of this function
  Welcome.call(this, name);
  this.order = order;
}

// Inherit 'sayHello()' methods from 'Welcome' prototype
RoomService.prototype = Object.create(Welcome.prototype);

// By default prototype object has 'constructor' property. 
// But as we created new object without this property  -  we have to set it manually,
// otherwise 'constructor' property will point to 'Welcome' class
RoomService.prototype.constructor = RoomService;

RoomService.prototype.announceDelivery = function() {
  return 'Your ' + this.order + ' has arrived!';
}
RoomService.prototype.deliverOrder = function() {
  return this.sayHello() + ' ' + this.announceDelivery();
}

var delivery = new RoomService('John', 'pizza');

delivery.sayHello();
// => Hello, John!,

delivery.announceDelivery();
// Your pizza has arrived!

delivery.deliverOrder();
// => Hello, John! Your pizza has arrived!