繁体   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