在没有自我执行的情况下包装JavaScript“类”?

时间:2011-12-23 17:29:35

标签: javascript

包装JavaScript“类”?

下面是一个用于显示消息的简单“类”。它存储输出HTML div,然后根据需要向其显示消息。

工作正常。出于可读性和封装的目的,我想在一个容器或JavaScript对象中的“类”的组件?最简单的方法是什么。

或者......有一种简单的方法吗?

目前唯一的容器是我用代码包围的注释。

/**
 *      Module  :       Model
 *      Name    :       -Message
 *      Input   :       div via the constructor
                        message type via display
 *      Output  :       TextStream via display to Control.sendInner
 *      Notes   :       Symmetric, client holds message location so needs extra variable
 */

var Message = function( div ) 
{
    this.div = document.getElementById( div ); 
};

Message.prototype.messages = 
{ 
    name:       'Please enter a valid name',
    email:      'Please enter a valid email',
    pass:       'Please enter passoword, 6-40 characters',
    url:        'Pleae enter a valid url',
    title:      'Pleae enter a valid title',
    tweet:      'Please enter a valid tweet',
    empty:      'Please complete all fields',
    empty_bm:   'Please complete all fields',
    same:       'Please make emails equal',
    taken:      'Sorry, that email is taken',
    validate:   'Please contact <a class="d" href="mailto:support@.com">support</a> to reset your password'
};

Message.prototype.display = function( type ) 
{
    Control.sendInner( this.div, this.messages[type] ) 
};      


/**      Message End        */

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你可以namespace使用自我调用函数(function(window, undefined) { var foo = 0; //private variable accessible only to code within this scope //Your class definition: window.Message = function( div ) { this.div = document.getElementById( div ); }; Message.prototype.message = //... //.... })(window); 这样做:

(function(window, undefined) {
    window.Class = function() {
        var private, variables, here;

        function privateFunc1(v) { here = v; }
        function privateFunc2() { return here; }

        return {
            publicSet: privateFunc1,
            publicGet: privateFunc2
        };
    }
})(window);

//Usage:
var c1 = new Class(), c2 = new Class();

c1.publicSet(true);
console.log(c1.publicGet(), c2.publicGet()); //output: true, undefined

但也许我误解了这个问题......

我在JS中创建类的常用方法是:

{{1}}

编辑为某些用途更改了一些代码