用于初始化私有变量的Javascript构造函数

时间:2012-11-19 00:46:07

标签: javascript

好的,我正在使用以下框架代码来创建Javascript库

var Device = (function(window, document, $) {
    function func_1(){
         return 1;
    }

    function func_2(){
        return 2;
    }

    var internalDevice = {
        func_1: func_1,
        func_2: func_2
    };
    return internalDevice; // expose functionality to the rest of the code
})(window, document, jQuery);

基本上,我会调用我的函数:Device.func_1();

我想添加一个构造函数,它将从get-go初始化一些私有变量,即一旦创建了对象,就不需要进行任何额外的函数调用。

我该怎么做?!

感谢。

3 个答案:

答案 0 :(得分:2)

可以尝试这种方式吗? private_1和private_2只能通过函数调用访问,而您可以使用Device()构造函数。

function Device(param1, param2) {
    var private_1= param1;
    var private_2= param2;

    this.func_1= function() {
        return private_1;                
    }

    this.func_2= function() {
        return private_2;            
    }
}

var myDevice = new Device(1, 2);
alert(myob.func_1()); 

或者可能是这样的:

var Device = (function(window, document) {
    var private_1;

    function init(param1) {
      private_1 = param1;
    }

    function func_1(){
         return private_1;
    }

    function func_2(){
        return 2;
    }

    var internalDevice = {
        func_1: func_1,
        func_2: func_2,
        init  : init
    };
    return internalDevice; // expose functionality to the rest of the code
})(window, document);

Device.init(10);
alert(Device.func_1())

答案 1 :(得分:1)

我设法解决了这个问题,这是我如何做到的:

var Device = (function(window, document, $) {
    var var_1 = 10,
    var_2 = 20,
    var_3;

    function init(){
         var_3 = 30;
    }

    function func_1(){
         return 1;
    }

    function func_2(){
         return 2;
    }

    var internalDevice = {
        init: init(),
        func_1: func_1,
        func_2: func_2
    };
    return internalDevice;
})(window, document, jQuery);

因此,当您调用Device.func_2();时,变量已经初始化。您可以在此处查看实时示例:http://jsfiddle.net/CZjYH/11/

我还将在init函数中实现Amplify.JS功能,作为将变量保存到本地或会话存储的方法。

干杯。

答案 2 :(得分:0)

var Device = (function(window, document, $, undefined)
{
    return $.extend(function()
    {
        // constructor
    },
    {
        prototype:
        {
            func_1: function func_1()
            {
                return 1;
            },
            func_2: function func_1()
            {
                return 2;
            }
        }
    });
})
(window, window.document, jQuery);

OR

var Device = (function(window, document, $, undefined)
{
    var DevicePrivate = function()
    {
        // constructor
    };

    DevicePrivate.prototype =
    {
        func_1: function()
        {
            return 1;
        },
        func_2: function()
        {
            return 2;
        }
    };

    return DevicePrivate;
})
(window, window.document, jQuery);
相关问题