JavaScript库模式

时间:2011-07-25 23:31:17

标签: javascript design-patterns

我正在试图找出创建JavaScript库(类)的基本模式。我希望这样做,它不会用一堆垃圾污染全局命名空间,但允许类具有实例变量和修改这些实例变量的公共方法。

考虑以下玩具示例。我想上课Foo。它应该包含一个实例成员bar,这是一个数字。 Foo应该有一个构造函数,它接受一个数字,并使用该数字初始化其实例bar。应该有一个实例方法可以在Foo对象上调用以修改bar。也许使用该库的代码如下所示:

var foo1 = new Foo(1);
var foo2 = new Foo(2);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "2"
foo2.changeBar(42);
console.log(foo1.bar); // should print "1"
console.log(foo2.bar); // should print "42"

结果foo.js将由Web应用程序使用,因此通过HTML中的脚本标记包含在内。

我已经对谷歌进行了一些搜索,但我还没有找到一个关于如何设计JavaScript类(用作库)的单一,简洁,通用的大纲。

3 个答案:

答案 0 :(得分:10)

(function () {
    Foo = function (num) {
         this.changeBar(num);
    };

    var privateMethod = function (x) {
        if (this.bar === 999) {
            this.bar = x;
        }
    };

    Foo.prototype.changeBar = function (num) {
        this.bar = num;
        privateMethod.call(this, 1);
    };

}());

这是最简单的方法。您不需要在闭包中包含定义,更多的是样式。

答案 1 :(得分:8)

建立在Evan的答案上,展示更多可能性。大多数正常情况只会使用其中一些。

(function() {
    //When we create variables inside a function they can only be seen by other
    // inner functions. Wraping all our code here makes sure noone gets to see
    // the private stuff.

    //The first opening parenthesis is required for Javascript to parse it
    //correctly though


    //this is the constructor function
    //Note how we set a global variable (Foo) to make it available outside.
    Foo = function(num, another_num) {

        this.changeBar(num);

        //sometimes you will want to make a method that modifies a variable
        //that can't be acessed via this.xxx. You can use a closure here for that
        //(there are some performance considerations though)

        this.baz = function(){
            console.log(another_num);
        }

        //Setting methods "by hand" like this is also useful if you want to
        //do multiple inheritance, since you can just set all methods of the
        //second class by hand here if you want.
    }

    //Things on Foo.prototype will be available for all Foo objects,
    // via prototypal inheritance magic.
    Foo.prototype.changeBar = function(num) {
        this.bar = num;
    }

    var a_secret_variable = 42;

    function my_private_function(){
        console.log(a_secret_variable);
    }

    //All private variables can be normaly used (by functions that can see them).
    Foo.prototype.use_magic = function(){
        my_private_function();
    }

}());
 //The "fake" function is imediatelly called,
 //so in the end all it does is create a inner scope.

答案 2 :(得分:3)

Module Pattern可能是目前使用最流行的模式。

var Foo = (function() {
    var _thisIsAPrivateVar;

    function thisIsAPrivateMethod() {
    }

    return {
        thisIsAPublicMethod : function() {
            // can still access the "private" variable and method
        }
    };

})();