DIV CSS 佈局教程網

深入理解 JavaScript(46):四種值得推薦的程式碼復用模式
編輯:關於JavaScript     

程式碼復用是工程素養的核心指標之一。本文整理四種經過實戰檢驗的復用模式——原型繼承、屬性拷貝、混入(mix-in)與借用方法,全部附有可運行的範例,都是值得納入日常開發工具箱的最佳實踐。

模式一:原型繼承

原型繼承的思路是讓父物件充當子物件的原型,藉由原型鏈上的查找達成繼承效果。

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

// 要繼承的父物件
var parent = {
    name: "Papa"
};

// 新物件
var child = object(parent);

// 測試
console.log(child.name); // "Papa"

// 父構造函式
function Person() {
    // an "own" property
    this.name = "Adam";
}
// 給原型添加新屬性
Person.prototype.getName = function () {
    return this.name;
};
// 創建新 person
var papa = new Person();
// 繼承
var kid = object(papa);
console.log(kid.getName()); // "Adam"

// 父構造函式
function Person() {
    this.name = "Adam";
}
Person.prototype.getName = function () {
    return this.name;
};
// 繼承
var kid = object(Person.prototype);
console.log(typeof kid.getName); // "function",因為是在原型裡定義的
console.log(typeof kid.name);    // "undefined",因為只繼承了原型

ECMAScript 5 提供了更便利的 Object.create:

var child = Object.create(parent);

var child = Object.create(parent, {
    age: { value: 2 } // ECMA5 descriptor
});
console.log(child.hasOwnProperty("age")); // true

屬性描述器可以做得更細緻:

// 首先,定義一個新物件 man
var man = Object.create(null);

// 接著,創建包含屬性的配置設置
// 屬性設置為可寫,可枚舉,可配置
var config = {
    writable: true,
    enumerable: true,
    configurable: true
};

// 通常使用 Object.defineProperty() 來添加新屬性(ECMAScript 5 支持)
// 現在,為了方便,我們自定義一個封裝函式
var defineProp = function (obj, key, value) {
    config.value = value;
    Object.defineProperty(obj, key, config);
}

defineProp(man, 'car', 'Delorean');
defineProp(man, 'dob', '1981');
defineProp(man, 'beard', false);

// 所以,繼承就可以這麼做了
var driver = Object.create( man );
defineProp (driver, 'topSpeed', '100mph');
driver.topSpeed // 100mph

這裡有個坑要注意:Object.create(null) 產生的物件原型為 undefined,也就是沒有 toString 與 valueOf 方法,因此直接 alert(man) 會出錯,但 alert(man.car) 完全沒問題。

模式二:拷貝所有屬性進行繼承

這種方式把父物件的所有屬性複製到子物件上,讓子物件得以使用父物件的資料。先看淺拷貝:

/* 淺拷貝 */
function extend(parent, child) {
    var i;
    child = child || {};
    for (i in parent) {
        if (parent.hasOwnProperty(i)) {
            child[i] = parent[i];
        }
    }
    return child;
}

var dad = { name: "Adam" };
var kid = extend(dad);
console.log(kid.name); // "Adam"

var dad = {
    counts: [1, 2, 3],
    reads: { paper: true }
};
var kid = extend(dad);
kid.counts.push(4);
console.log(dad.counts.toString()); // "1,2,3,4"
console.log(dad.reads === kid.reads); // true

最後一行正是淺拷貝的隱憂:dad 與 kid 的 reads 指向同一個記憶體位置,改一邊另一邊也跟著變。深拷貝則是解法:

/* 深拷貝 */
function extendDeep(parent, child) {
    var i,
        toStr = Object.prototype.toString,
        astr = "[object Array]";

    child = child || {};

    for (i in parent) {
        if (parent.hasOwnProperty(i)) {
            if (typeof parent[i] === 'object') {
                child[i] = (toStr.call(parent[i]) === astr) ? [] : {};
                extendDeep(parent[i], child[i]);
            } else {
                child[i] = parent[i];
            }
        }
    }
    return child;
}

var dad = {
    counts: [1, 2, 3],
    reads: { paper: true }
};
var kid = extendDeep(dad);

kid.counts.push(4);
console.log(kid.counts.toString()); // "1,2,3,4"
console.log(dad.counts.toString()); // "1,2,3"

console.log(dad.reads === kid.reads); // false
kid.reads.paper = false;

深拷貝之後兩邊徹底分家,這才是多層巢狀結構下安全的做法。

模式三:混合(mix-in)

混入是把一個或多個物件的屬性、方法複製到另一個物件上,靈活度非常高。

function mix() {
    var arg, prop, child = {};
    for (arg = 0; arg < arguments.length; arg += 1) {
        for (prop in arguments[arg]) {
            if (arguments[arg].hasOwnProperty(prop)) {
                child[prop] = arguments[arg][prop];
            }
        }
    }
    return child;
}

var cake = mix(
        { eggs: 2, large: true },
        { butter: 1, salted: true },
        { flour: '3 cups' },
        { sugar: 'sure!' }
    );

console.dir(cake);

若只想混入部分屬性,可以把方法名稱當成額外參數傳入:

// Car
var Car = function (settings) {
    this.model = settings.model || 'no model provided';
    this.colour = settings.colour || 'no colour provided';
};

// Mixin
var Mixin = function () { };
Mixin.prototype = {
    driveForward: function () {
        console.log('drive forward');
    },
    driveBackward: function () {
        console.log('drive backward');
    }
};

// 定義的 2 個參數分別是被混入的物件(reciving)和從哪裡混入的物件(giving)
function augment(receivingObj, givingObj) {
    // 如果提供了指定的方法名稱的話,也就是參數多餘 3 個
    if (arguments[2]) {
        for (var i = 2, len = arguments.length; i < len; i++) {
            receivingObj.prototype[arguments[i]] = givingObj.prototype[arguments[i]];
        }
    }
    // 如果不指定第 3 個參數,或者更多參數,就混入所有的方法
    else {
        for (var methodName in givingObj.prototype) {
            // 檢查 receiving 物件內部不包含要混入的名字,如果包含就不混入了
            if (!receivingObj.prototype[methodName]) {
                receivingObj.prototype[methodName] = givingObj.prototype[methodName];
            }
        }
    }
}

// 給 Car 混入屬性,但是值混入 'driveForward' 和 'driveBackward'
augment(Car, Mixin, 'driveForward', 'driveBackward');

// 創建新物件 Car
var vehicle = new Car({ model: 'Ford Escort', colour: 'blue' });

// 測試是否成功得到混入的方法
vehicle.driveForward();
vehicle.driveBackward();

模式四:借用方法

一個物件借用另一個物件的一兩個方法,而兩者之間不必有任何繼承關係,靠 apply/call 改變 this 指向即可。

var one = {
    name: 'object',
    say: function (greet) {
        return greet + ', ' + this.name;
    }
};

// 測試
console.log(one.say('hi')); // "hi, object"

var two = {
    name: 'another object'
};

console.log(one.say.apply(two, ['hello'])); // "hello, another object"

// 將 say 賦值給一個變數,this 將指向到全局變數
var say = one.say;
console.log(say('hoho')); // "hoho, undefined"

// 傳入一個回調函式 callback
var yetanother = {
    name: 'Yet another object',
    method: function (callback) {
        return callback('Hola');
    }
};
console.log(yetanother.method(one.say)); // "Hola, undefined"

function bind(o, m) {
    return function () {
        return m.apply(o, [].slice.call(arguments));
    };
}

var twosay = bind(two, one.say);
console.log(twosay('yo')); // "yo, another object"

// ECMAScript 5 給 Function.prototype 添加了一個 bind() 方法,以便很容易使用 apply() 和 call()
if (typeof Function.prototype.bind === 'undefined') {
    Function.prototype.bind = function (thisArg) {
        var fn = this,
            slice = Array.prototype.slice,
            args = slice.call(arguments, 1);
        return function () {
            return fn.apply(thisArg, args.concat(slice.call(arguments)));
        };
    };
}

var twosay2 = one.say.bind(two);
console.log(twosay2('Bonjour')); // "Bonjour, another object"

var twosay3 = one.say.bind(two, 'Enchanté');
console.log(twosay3()); // "Enchanté, another object"

這裡有個容易踩的雷:把方法從物件上摘下來單獨呼叫時,this 會掉回全域物件,於是 this.name 變成 undefined。bind 的價值就在於把 this 牢牢綁定住,同時還能預先塞入部分參數(partial application)。

該怎麼選

四種模式各有適用場合:需要清晰的型別層級時用原型繼承;只是想把一組設定資料搬過來時用屬性拷貝(記得判斷是否需要深拷貝);想替既有類別補上幾個能力時用混入;只想臨時借用一兩個方法、又不想牽動繼承結構時,借用方法最合適。理解它們的差異,比死記語法更重要。

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