JavaScript Object Oriented Programming: All-in-one Constructor Pattern

JavaScript

所有的 method 和 property 都放在 consctructor 中,而不使用 prototype。

Declaration

function Animal(name) {
  this.name = name;
  this.run = function() {
    console.log('running ' + this.name);
  };
}

var animal = new Animal('Foxie');
animal.run();

Inheritance

建立 Rabbit 這個建構子,並繼承 Animal。

function Rabbit(name) {
  Animal.apply(this, arguments);
  this.bounce = function() {
    console.log('bouncing ' + this.name);
  };
}

var rabbit = new Rabbit('Rab');
rabbit.bounce();
rabbit.run();

Overriding (polymorphism)

function Rabbit(name) {
  Animal.apply(this, arguments);
  var parentRun = this.run; // keep parent method
  this.run = function() {
    console.log('bouncing ' + this.name);
    parentRun.apply(this); // call parent method
  };
}

var rabbit = new Rabbit('Rab');
rabbit.run(); // inherited method

Private/protected methods(encapsulation)

在建構子之內的變數和函數視為 private,設定給 this 的視為 public。

function Animal(name) {
  this.name = name;
  this.run = function() {
    console.log('running ' + this.name);
  };
}

function Rabbit(name) {
  Animal.call(this, 'Mr.' + name.toUpperCase());
  var created = new Date(); //private
  function sayHi() {
    //private
    console.log("I'm talking rabbit " + name);
  }
  this.report = function() {
    sayHi.apply(this);
    console.log('Created at ' + created);
  };
}

var rabbit = new Rabbit('Rab');
rabbit.report();

protected method 並沒有實質上的支援,可參考Private/protected methods (encapsulation)

Summary

Comparison with pseudo-classical pattern

References


這篇文章的原始位置在這裡-JavaScript Object Oriented Programming - All-in-one Constructor Pattern

由於部落格搬遷至此,因此在這裡放了一份,以便閱讀;部份文章片段也做了些許修改,以期提供更好的內容。

javascript prototype javascript

Summer Tang
Sponsored
Summer Tang 一對一諮詢
Summer|TSMC 主任工程師|擁有 15 年資深 Web 架構經驗,職涯歷經跨國頂尖企業與新創。專精於高流量企業級應用開發,核心技術涵蓋微前端、效能優化、測試自動化與 SEO。曾出版多本技術著作,並多次擔任 MOPCON、WebConf 等大型技術年會講者。
了解更多 →