JavaScript Object Oriented Programming: All-in-one Constructor Pattern
07 Feb 2016所有的 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
- 在建構子完整描述物件。
- 在目前物件呼叫父建構子後完成繼承。
- 在建構子之內的變數和函數視為 private,設定給 this 的視為 public。
- protected method 並沒有實質上的支援,撰寫規則是使用底線「_」。
- 使用在 this 中覆寫屬性,而也會保留原先的 property 來重複使用。
Comparison with pseudo-classical pattern
- 在 All-in-one Constructor Pattern 無法使用
rabbit instanceof Animal
,因為沒有做設定 prototype 的動作。 - 速度較慢且需要較多記憶體。由於每一個物件都擁有自己的 method,而非使用 prototype 共享。
- 實作 private method 和 property,是較為安全和快速的。
References
這篇文章的原始位置在這裡-JavaScript Object Oriented Programming - All-in-one Constructor Pattern
由於部落格搬遷至此,因此在這裡放了一份,以便閱讀;部份文章片段也做了些許修改,以期提供更好的內容。