簡體   English   中英

如何編寫簡單,可擴展,模塊化的Javascript

[英]How to write simple, extensible, modular Javascript

我需要一種機制,人們可以用他們自己的模塊擴展我的基本代碼 - 但我很難想出一個簡單的機制來做到這一點。

示例:用戶可以擴展的名為“test”的函數。 每個用戶模塊都在原始模塊之后加載 - 因此每個用戶模塊都需要在最后一個模塊上構建(它們加載的順序無關緊要或可以通過命名來控制)

我開始玩這樣的東西

var test = function() { // the master function
    console.log("1");
}

var ltest = test; // module 1
var test = function() {
    ltest();
    console.log("2");
}

var ltest2 = test; // module 2
var test = function() {
    ltest2();
    console.log("3");
}

然后,當調用'test'時,它將運行每個人的代碼(假設沒有人忘記他們的回調!!)

這是有效的,但它依賴於每個模塊聲明它自己的,獨特的'回調'變量(ltest,ltest2) - 如果有人使用相同的變量,我們將得到'超出調用堆棧',因為這些變量在范圍內是全局的。 。

任何人都可以建議一個更聰明/更好的系統 - 還是指出一些相同的例子?

繼承有很多材料,但我不想創建擴展舊的東西的新東西 - 我只是想擴展舊的!

ps從模塊模式中獲取匿名函數 - 我得到了這個

var test = function() {
    console.log("1");
}

(function() {
    var oldtest = test;
    test = function() {
        oldtest();
        console.log("2");
    }
}())

(function() {
    var oldtest = test;
    test = function() {
        oldtest();
        console.log("3");
    }
}())

這可能是我問題最簡單的解決方案 - 但不一定是最好的系統(因為它依賴於作者記住回調代碼 - 一個狡猾的模塊會破壞一切)

模塊模式是您所需要的。

特別是'增強'或'松散增強'模式:

var MODULE = (function (my) {
    var old_moduleMethod = my.moduleMethod;

    my.moduleMethod = function () {
        // method override, has access to old through old_moduleMethod...
    };

    return my;
}(MODULE || {}));

你可以做這樣的功能

function extendFunction(fn, pre, post) {
    return function () {
        var arg = arguments;
        if (pre) arg = pre.apply(this, arg);   // call pre with arguments
        arg = fn.apply(this, arg);             // call fn with return of pre
        if (post) arg = post.apply(this, arg); // call post with return of fn
        return arg;
    };
}

然后擴展如下

var test = function () { // the master function
    console.log("1");
};
test = extendFunction(
    test, // function to extend
    null, // thing to do first
    function() {console.log("2");} // thing to do after
);
test = extendFunction(
    test,
    null,
    function() {console.log("3");}
);
test(); // 1, 2, 3

這與“擴展”的正常含義非常不同,在這里你給對象賦予新屬性或設置原型鏈,以及通常涉及將所有代碼包裝在函數表達式中的 “模塊”,這樣你就不會污染命名空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM