How to make a private static array in a javascript class? - javascript

I want to make a static array in a javascript class, for this I do:
var Manager = (function () {
function Manager() {
var ubications = new ArrayList();
this.ubicationsArray = function () {
return(ubication);
};
}
Manager.prototype.addUbication = function (ubication) {
Manager.ubicationsArray().add(ubication);
};
Manager.prototype.getUbication = function (index) {
return Manager.ubicationsArray().get(index);
};
Manager.prototype.sizeOfUbications = function () {
return Manager.ubicationsArray().size();
};
return Manager;
}());
Manager["__class"] = "Manager";
Where ubications is the static array and the function ubicationsArray is the public function to acces the array.
I try to use this code with:
var ubication = new Ubication(123,456);
var manager = new Manager();
manager.addUbication(ubication);
alert(manager.sizeOfUbications());
But I got this error:
Uncaught TypeError: Manager.ubicationsArray is not a function
How is the correct way to use static arrays in a javascript code?

Currently, JavaScript can only do privacy with respect to function scope.
function Manager () {
}
Manager.prototype = (function (){
var ubications = [];
return {
addUbication: function (u) {
ubications.push(u);
},
getUbication: function (index) {
return ubications[index];
},
sizeOfUbications: function () {
return ubications.length;
}
};
})();

Inside your constructor function, this.ubicationsArray assigns a property to the instance of the object, not the constructor itself.
Perhaps you want something like this:
function Manager() {
}
var ubications = new ArrayList();
Manager.ubicationsArray = function () {
return(ubication);
};
Note that this property isn't really "private". This would be more-private:
var Manager = (function () {
function Manager() {
}
var ubications = new ArrayList();
Manager.prototype.addUbication = function (ubication) {
ubications.add(ubication);
};
Manager.prototype.getUbication = function (index) {
return ubications.get(index);
};
Manager.prototype.sizeOfUbications = function () {
return ubications.size();
};
return Manager;
}());
Manager["__class"] = "Manager";

Related

Javascript - 'Function' is not a function singleton pattern

I've been trying to learn Javascript. This is my code - I'm trying to implement a singleton - but for some reason, I get the error setMessage is not a function in the line firstInstance.setMessage("Message");. I have no idea what I'm doing wrong - any help would be greatly appreciated.
`
var mySingleton = (function () {
var instance;
var message;
function getInstance() {
if (!instance) instance = new Object();
return instance;
}
function setM (newMessage) {
message = newMessage;
return;
}
function getM() {
return message;
}
return {
createInstance:getInstance,
setMessage:setM,
getMessage:getM
}
})();
var firstInstance = mySingleton.createInstance();
var secondInstance = mySingleton.createInstance();
//set messages
firstInstance.setMessage("Message");
console.log(firstInstance.getMessage());
console.log(secondInstance.getMessage());
//change messages
secondInstance.setMessage("New");
console.log(firstInstance.getMessage());
console.log(secondInstance.getMessage());`
The setMessage and getMessage need to be on the instance you create, not in the object returned with the createInstance:
var mySingleton = (function() {
let instance;
let message;
function createInstance() {
if (!instance) instance = { setMessage, getMessage };
return instance;
}
function setMessage(newMessage) {
message = newMessage;
}
function getMessage() {
return message;
}
return { createInstance }
})();
var firstInstance = mySingleton.createInstance();
var secondInstance = mySingleton.createInstance();
firstInstance.setMessage("Message");
console.log(firstInstance.getMessage());
console.log(secondInstance.getMessage());
secondInstance.setMessage("New");
console.log(firstInstance.getMessage());
console.log(secondInstance.getMessage())

A prototype-less, new-less, one-instance-only javascript object?

This doesn't work.
var genericClickHandler = function () {
this.handlers = [];
if (console && console.log) {
console.log("this:", this);
console.log("event:", event);
}
};
genericClickHandler.addHandler = function (handlerSpec) {
this.handlers.push(handlerSpec);
return this;
};
genericClickHandler.executeHandler = function (handlerName) {
for (var i = 0; i < this.handlers.length; i++) {
if (handlerName === this.handlers[i][0]) {
this.handlers[i][1]();
}
}
return this;
};
It doesn't work because the addHandler can't see the this.handlers in genericClickHandler.
Anyway what I'm after is function that gets defined once, but has methods and properties. I want to be able to use the function with Google Maps like this:
heatmap.addListener("click", genericClickHandler)
circle.addListener("click", genericClickHandler)
polygons.addListener("click", genericClickHandler)
So in the first instance, it only reports the this and event object. However, I then want to write code which extends the genericClickHandler dynamically so that it can implement map-object-specific behaviour.
Here's an example of what I meant using an object rather than a function.
var genericClickHandler = {
handlers: []
};
genericClickHandler.addHandler = function (name, fn) {
this.handlers.push([name, fn]);
return this;
};
genericClickHandler.executeHandler = function (name) {
for (var i = 0, l = this.handlers.length; i < l; i++) {
if (this.handlers[i][0] === name) this.handlers[i][1]();
}
};
genericClickHandler.addHandler('click', function () {
console.log('hi');
});
genericClickHandler.addHandler('click', function () {
console.log('hallo again');
});
genericClickHandler.executeHandler('click'); // hi... hallo again
DEMO
if you want to create an object, here you can see 2 ways to do the same thing, javascript got multiple way to write the same things.
var genericClickHandler = function()
{
this.handlers = [];
this.addHandler = function (handlerSpec)
{
this.handlers.push(handlerSpec);
return this;
},
this.executeHandler = function (handlerName)
{
this.handlers[handlerName]();
return this;
}
};
//sample:
var tmp = new genericClickHandler();
console.log(tmp.handlers);
console.log(tmp.addHandler("TEST"));
Another way to write the same object, but more optimised : prototype will be stored once for each object
var genericClickHandler = function(){}
genericClickHandler.prototype =
{
handlers:[],
addHandler : function (handlerSpec)
{
this.handlers.push(handlerSpec);
return this;
},
executeHandler : function (handlerName)
{
this.handlers[handlerName]();
return this;
}
}
//sample:
var tmp = new genericClickHandler();
console.log(tmp.handlers);
console.log(tmp.addHandler("TEST"));

Accessing private methods of a JS Function

I have following javascript code
function MyFunc () {
var add = function () {
return "Hello from add";
};
var div = function () {
return "Hello from div";
};
var funcCall = function (obj) {
if (!obj) {
throw new Error("no Objects are passed");
}
return obj.fName();
};
return {
func: function (obj) {
funcCall(obj);
}
};
}
var lol = new MyFunc();
When lol.func({fName: add}); is passed it should invoke the function private function add or when lol.func({fName: div}); is passed it should invoke the private div function. What i have tried does not work. How can i achieve this.
DEMO
In this case it's better to store your inner function in the object so you can easily access this with variable name. So if you define a function "map"
var methods = {
add: add,
div: div
};
you will be able to call it with methods[obj.fName]();.
Full code:
function MyFunc() {
var add = function () {
return "Hello from add";
};
var div = function () {
return "Hello from div";
};
var methods = {
add: add,
div: div
};
var funcCall = function (obj) {
if (!obj) {
throw new Error("no Objects are passed");
}
return methods[obj.fName]();
};
return {
func: function (obj) {
return funcCall(obj);
}
};
}
var lol = new MyFunc();
console.log( lol.func({fName: 'add'}) );
When you pass lol.func({fName: add}) add is resolved in the scope of evaluating this code, not in the scope of MyFunc. You have to either define it in that scope like:
function MyFunc () {
var add = function () {
return "Hello from add";
};
var div = function () {
return "Hello from div";
};
var funcCall = function (obj) {
if (!obj) {
throw new Error("no Objects are passed");
}
return obj.fName();
};
return {
add: add,
div: div,
func: function (obj) {
funcCall(obj);
}
};
}
var lol = new MyFunc();
lol.func({fName: lol.add});
Or use eval.

Is there any other way to implement Singleton Pattern in javascript?

Trying to implement singleton pattern in javascript following some tutorials. Just wondering if there is any other way to implement the same ?
var singleton = (function(){
var getInstance; //private variable
var createWidget = function(){
var todayDate = new Date(); //private
var addCSS = function(){
console.log('THis is my css function');
};
var getDropDownData = function(){
console.log('This is my getDropDownData function');
};
return {
getDropDownData : getDropDownData,
addCSS: addCSS
};
};
return {
getInstance: function(){
if(!getInstance) {
getInstance = createWidget();
}
return getInstance;
}
};
})();
var obj = singleton.getInstance();
Implementing it by running anonymous function at onLoad and assiging it to some variable. Can we implement it without running this function at onLoad ?
You could always write a function to abstract away the boilerplate for writing singletons. For example this is what I would do:
function singleton(prototype) {
var instance = null;
return {
getInstance: function () {
if (instance === null) {
var Instance = prototype.init || function () {};
Instance.prototype = prototype;
instance = new Instance;
} return instance;
}
};
}
Then you can use this function to create singletons as follows:
var Widget = singleton({
init: function () {
var todayDate = new Date; // private
},
addCSS: function () {
console.log("This is my addCSS function.");
},
getDropDownData: function () {
console.log("This is my getDropDownData function.");
}
});
After that you use the singleton as you normally would:
var widget = Widget.getInstance();
Hope that helps.

access public method in extended class from protected method in extending class - javascript inheritance

i'm practicing with Javascript Inheritance, my first try is following code:
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
base_class.call(this);
var _data = 'test';
function _getData() {
return this.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return this.get();
}
this.init(_data);
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
to that point i am really happy with my solution, but there is one problem
that i dont get resolved.
the "getDataOther" method don`t return the stored data from the base class,
because i cannot access the public "get" class from the protected "_getData" method in the new_class.
How can i get that running ?
Thanks in advance.
Ps.: Please excuse my poor English
If you comment out the this.init function (which overwrites the base_class _data field) and make the new_class's getData function just return _data, you should be able to get distinct variables.
var base_class = function()
{
var _data = null;
function _get() {
return _data;
}
this.get = function() {
return _get();
}
this.init = function(data) {
_data = data;
}
}
var new_class = function() {
var self = this; //Some browsers require a separate this reference for
//internal functions.
//http://book.mixu.net/ch4.html
base_class.call(this);
var _data = 'test';
function _getData() {
return self.get();
}
this.getDataOther = function() {
return _getData();
}
this.getData = function() {
return _data; //Changed this line to just return data
//Before, it did the same thing as _getData()
}
//this.init(_data); //Commented out this function (it was changing the base_class' data)
}
new_class.prototype = base_class.prototype;
var instance = new new_class();
alert(instance.getData());
alert(instance.getDataOther());
Your english is fine by the way :)

Categories