萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

深入理解 JavaScript 設計模式:建構函數模式詳解與最佳實踐

建構函數基礎概念

JavaScript 沒有類,但有特殊的建構函數。透過 new 調用,this 指向新建立的物件,可在建構函數內宣告屬性與方法。

基本用法

function Car(model, year, miles) {
  this.model = model;
  this.year = year;
  this.miles = miles;
  this.output = function() {
    return this.model + "走了" + this.miles + "公里";
  };
}
var tom = new Car("大叔", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);
console.log(tom.output());  // 大叔走了20000公里
console.log(dudu.output()); // Dudu走了5000公里
問題:每個實例都擁有獨立的 output 函式,記憶體浪費。

優化一:共用函式引用

function Car(model, year, miles) {
  this.model = model; this.year = year; this.miles = miles;
  this.output = formatCar; // 指向外部函式
}
function formatCar() { return this.model + "走了" + this.miles + "公里"; }

優化二:原型模式(推薦)

function Car(model, year, miles) {
  this.model = model; this.year = year; this.miles = miles;
}
Car.prototype.output = function() {
  return this.model + "走了" + this.miles + "公里";
};
var tom = new Car("大叔", 2009, 20000);
var dudu = new Car("Dudu", 2010, 5000);
console.log(tom.output()); // 共用同一個 output 函式

慣例:建構函數首字母大寫,區分一般函式。

不使用 new 會發生什麼?

// 直接呼叫
Car("大叔", 2009, 20000); // this 指向 window
console.log(window.output()); // "大叔走了20000公里"
var tom = Car("大叔", 2009, 20000);
console.log(typeof tom); // "undefined"

// 使用 call 改變 this
var o = {};
Car.call(o, "Dudu", 2010, 5000);
console.log(o.output()); // "Dudu走了5000公里"

強制使用 new(防呆模式)

function Car(model, year, miles) {
  if (!(this instanceof Car)) {
    return new Car(model, year, miles);
  }
  this.model = model; this.year = year; this.miles = miles;
  this.output = function() { return this.model + "走了" + this.miles + "公里"; };
}
var tom = new Car("大叔", 2009, 20000);
var dudu = Car("Dudu", 2010, 5000); // 自動補 new
console.log(typeof dudu); // "object"
console.log(dudu.output()); // "Dudu走了5000公里"

原始包裝函式

JS 提供 Number、String、Boolean 包裝物件:

// 不推薦
var s = new String("my string");
var n = new Number(101);
var b = new Boolean(true);

// 推薦:使用字面量
var s = "my string";
var n = 101;
var b = true;

差異示範

// 原始字串
var greet = "Hello there";
greet.smile = true;
console.log(typeof greet.smile); // "undefined" (原始值無法動態加屬性)

// 包裝物件
var greet = new String("Hello there");
greet.smile = true;
console.log(typeof greet.smile); // "boolean" (物件可加屬性)

建構函數模式是 JavaScript 物件導向的基石。掌握 new、prototype、this 綁定機制,並善用強制 new 模式與原型共享方法,能寫出記憶體效率高、可維護性強的代碼。

copyright © 萬盛學電腦網 all rights reserved