Reputation: 11876
Ok, so I'm using the following skeleton code to create a Javascript Library
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);
Essentially, I would call my functions like so: Device.func_1();
.
I'm looking to add a constructor that will initialize some private variables from the get-go i.e. as soon as the object is created, and without having to make any extra function call(s).
How do I do this?!
Thanks.
Upvotes: 1
Views: 1008
Reputation: 11876
I managed to figure this one out, here's how I did it:
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);
So when you call Device.func_2();
, the variables would already have been initialized. You can see a live example here: http://jsfiddle.net/CZjYH/11/
I am also going to be implementing Amplify.JS functionality inside the init
function as a way of persisting my variables to local or Session storage.
Cheers.
Upvotes: 1
Reputation: 221
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);
Upvotes: 0
Reputation: 1167
May be try this way? private_1 and private_2 can only be accessible through function calls while you can use Device() constructor.
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());
or may be like this:
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())
Upvotes: 2