DIV CSS 佈局教程網

JavaScript 面向對象編程:繼承、封裝、多態與抽象
編輯:JavaScript基礎知識     

面向對象程序設計(Object-oriented programming,OOP)是一種編程范型,也是一種軟件開發方法。它把對象作為程序的基本單元,將數據與行為封裝在一起,從而提升代碼的重復用性、靈活性與可擴展性。對象則是類的實例。

一般討論 OOP 會涉及四件事:繼承、封裝、多態、抽象。下面逐一在 JS 中落地。

一、繼承

對象形式的繼承:淺拷貝

var Person = {
  name: 'allin',
  age: 18,
  address: { home: 'home', office: 'office' },
  schools: ['x', 'z']
};
var programer = { language: 'js' };

function extend(p, c) {
  var c = c || {};
  for (var prop in p) {
    c[prop] = p[prop];
  }
}
extend(Person, programer);

programer.name;          // allin
programer.address.home;  // home
programer.address.home = 'house';
Person.address.home;     // house,父對象被連帶修改

缺陷很明顯:引用類型只拷了地址,兩者指向同一份內存,改子對象會污染父對象。

深拷貝

function extendDeeply(p, c) {
  var c = c || {};
  for (var prop in p) {
    if (typeof p[prop] === "object") {
      c[prop] = (p[prop].constructor === Array) ? [] : {};
      extendDeeply(p[prop], c[prop]);
    } else {
      c[prop] = p[prop];
    }
  }
}

extendDeeply(Person, programer);
programer.address.home = 'allin';
Person.address.home;   // home,父對象不受影響

call / apply 借用構造函數

function Parent() {
  this.name = "abc";
  this.address = { home: "home" };
}
function Child() {
  Parent.call(this);
  this.language = "js";
}

Object.create()

var p = { name: 'allin' };
var obj = Object.create(p);
obj.name;   // allin

Object.create() 是 ES5 才引入的 new 替代方案,可以自己模擬:

function myCreate(o) {
  function F() {}
  F.prototype = o;
  return new F();
}

var p = { name: 'allin' };
var obj = myCreate(p);
obj.name;   // allin

主流瀏覽器(含 IE9)都已支持,遇到老環境可自行補上:

if (!Object.create) {
  Object.create = function (o) {
    function F() {}
    F.prototype = o;
    return new F();
  };
}

類式繼承

function Person(name, age) {}
Person.prototype.headCount = 1;
Person.prototype.eat = function () {
  console.log('eating...');
};

function Programmer(name, age, title) {}
Programmer.prototype = Object.create(Person.prototype); // 建立繼承
Programmer.prototype.constructor = Programmer;          // 修正 constructor 指向

調用父類方法:構造器用 apply 借用,原型方法則顯式指定 this。

function Person(name, age) {
  this.name = name;
  this.age = age;
}
Person.prototype.headCount = 1;
Person.prototype.eat = function () {
  console.log('eating...');
};

function Programmer(name, age, title) {
  Person.apply(this, arguments);   // 調用父類構造器
}
Programmer.prototype = Object.create(Person.prototype);
Programmer.prototype.constructor = Programmer;
Programmer.prototype.language = "js";
Programmer.prototype.work = function () {
  console.log('i am working code in ' + this.language);
  Person.prototype.eat.apply(this, arguments);   // 調用父類原型方法
};

二、封裝

命名空間

JS 沒有原生命名空間,用對象模擬即可:

var app = {};          // 命名空間 app

app.module1 = {
  name: 'allin',
  f: function () { console.log('hi robot'); }
};

app.module1.name;   // "allin"
app.module1.f();    // hi robot

靜態成員

function Person(name) {
  var age = 100;
  this.name = name;
}
Person.walk = function () { console.log('static'); };
Person.walk();   // static

私有與公有

function Person(id) {
  // 私有屬性與方法
  var name = 'allin';
  var work = function () { console.log(this.id); };

  // 公有屬性與方法
  this.id = id;
  this.say = function () {
    console.log('say hello');
    work.call(this);
  };
}

var p1 = new Person(123);
p1.name;    // undefined,私有
p1.id;      // 123,公有
p1.say();   // say hello / 123

模塊化

var moduleA = function () {
  var prop = 1;          // 私有
  function func() {}     // 私有
  return { func: func, prop: prop };
}();                     // 立即執行匿名函數

或者用 new 的寫法:

moduleA = new function () {
  var prop = 1;
  function func() {}
  this.func = func;
  this.prop = prop;
};

兩種寫法都能保證 prop、func 不洩露到全局作用域。

三、多態

模擬方法重載

arguments 能拿到實際傳入的參數個數,據此可以模擬重載。

function demo(a, b) {
  console.log(demo.length);        // 形參個數
  console.log(arguments.length);   // 實參個數
  console.log(arguments[0]);       // 第一個實參
  console.log(arguments[1]);       // 第二個實參
}
demo(4, 5, 6);

可變長參數求和:

function add() {
  var total = 0;
  for (var i = arguments.length - 1; i >= 0; i--) {
    total += arguments[i];
  }
  return total;
}
console.log(add(1));         // 1
console.log(add(1, 2, 3));   // 6

按參數個數分支:

function fontSize() {
  var ele = document.getElementById('js');
  if (arguments.length == 0) {
    return ele.style.fontSize;      // 無參:讀取
  } else {
    ele.style.fontSize = arguments[0]; // 有參:設置
  }
}

按參數類型分支:

function setting() {
  var ele = document.getElementById('js');
  if (typeof arguments[0] === "object") {
    for (var p in arguments[0]) {
      ele.style[p] = arguments[0][p];
    }
  } else {
    ele.style.fontSize = arguments[0];
    ele.style.backgroundColor = arguments[1];
  }
}
setting(18, 'red');
setting({ fontSize: 20, backgroundColor: 'green' });

方法重寫

function F() {}
var f = new F();

F.prototype.run = function () { console.log('F'); };
f.run();   // F

f.run = function () { console.log('fff'); };
f.run();   // fff,實例上的屬性優先於原型

四、抽象類

JS 沒有 abstract 關鍵字,可以在構造器裡拋異常來阻止直接實例化:

function DetectorBase() {
  throw new Error('Abstract class can not be invoked directly!');
}
DetectorBase.prototype.detect = function () {
  console.log('Detection starting...');
};
DetectorBase.prototype.stop = function () {
  console.log('Detection stopped.');
};
DetectorBase.prototype.init = function () {
  throw new Error('Error');
};

// new DetectorBase();  // Uncaught Error: Abstract class can not be invoked directly!

function LinkDetector() {}
LinkDetector.prototype = Object.create(DetectorBase.prototype);
LinkDetector.prototype.constructor = LinkDetector;

var l = new LinkDetector();
l.detect();   // Detection starting...
l.init();     // Uncaught Error: Error,子類按需覆寫

子類繼承後即可使用父類的通用實現,而必須定製的方法留待子類覆寫——這正是抽象基類的價值所在。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved