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

所有的 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
comments powered by Disqus