包装JavaScript“类”W / out自我执行

Wrapping a JavaScript "class" w/ out self execution?

本文关键字:out 自我 执行 JavaScript 包装      更新时间:2023-09-26

包装JavaScript "类"?

下面是一个显示消息的简单"类"。它存储输出的HTMLdiv,然后根据需要向它显示消息。

很好。出于可读性和封装的目的,我希望将"类"的组件放在各种容器或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        */

如果我理解正确,您可以使用自调用函数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);

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

我在JS中创建类的常用方法是:
(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

EDIT修改了一些代码