Javascript - 'Function' is not a function singleton pattern - javascript

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())

Related

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

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";

JavaScript: Executing chained methods in any order

Suppose I have a function called log which simply prints the given string.
Can I refactor my code so both of these function could work?
log("needsChange").doSomethingWithTheStringBeforePrintingIt();
log("perfectStringToPrint");
You can do something similar with nested class logics:
var log = (function() {
//Class
var _log = (function() {
function _log(message) {
this.message = message;
}
_log.prototype.doSomethingWithTheStringBeforePrintingIt = function() {
this.message = this.message.split("").reverse().join("");
return this;
};
_log.prototype.capitalizeFirstWord = function() {
this.message = this.message[0].toUpperCase() + this.message.substr(1);
return this;
};
_log.prototype.print = function() {
return this.message;
};
return _log;
}());
//Instancer function
return function log(message) {
//Return instance of class
return new _log(message);
};
})();
//Test
console.log(log("needsChange")
.doSomethingWithTheStringBeforePrintingIt()
.capitalizeFirstWord()
.print(), log("perfectStringToPrint")
.print());
If you are comfortable with promises, then you can do something like this:
var logger = (function() {
//Class
var _log = (function() {
function _log(message) {
var _this = this;
this.message = message;
this.promise = null;
this.promises = [];
this.promise = Promise.all(this.promises).then(function(values) {
console.log(_this.message); // [3, 1337, "foo"]
});
}
_log.prototype.reverse = function() {
var self = this;
this.promises.push(new Promise(function(resolve, reject) {
setTimeout(resolve, 0, (function() {
self.message = self.message.split("").reverse().join("");
})());
}));
return this;
};
_log.prototype.capitalizeFirst = function() {
var self = this;
this.promises.push(new Promise(function(resolve, reject) {
setTimeout(resolve, 0, (function() {
self.message = self.message[0].toUpperCase() + self.message.substr(1);
})());
}));
return this;
};
return _log;
}());
//Instancer function
return function log(message) {
//Return instance of class
return new _log(message);
};
})();
//Test
logger("needsChange").reverse().capitalizeFirst().reverse(); //Capitalizes last letter
logger("perfectStringToPrint");
This removes the need for a .print call.
I have made a library to solve this issue
https://github.com/omidh28/clarifyjs

Java script visitor sample is not working

I need to use logic like visitor pattern and I've created new
sample which failed in visitor.visit(self); and I got error undefined is not a function,
any idea what am I missing?
var Entity = function (file,name) {
var self = this;
var name;
var type;
var log = {};
this.setName = function (name) {
this.name = name;
};
this.accept = function (visitor) {
visitor.visit(self);
};
this.getName = function () {
return name;
};
this.getType = function () {
return type;
};
this.getLog = function () {
return log;
};
};
//Start using visitor
var verifyFile = function () {
this.visit = function (file) {
alert("test");
};
};
function test(){
var file = new Entity();
file.accept(verifyFile);
};
You are injecting a function that defines a function, but your code is looking for an object that contains a function - see below
var Entity = function(file, name) {
var self = this;
var name;
var type;
var log = {};
this.setName = function(name) {
this.name = name;
};
this.accept = function(visitor) {
visitor.visit(self);
};
this.getName = function() {
return name;
};
this.getType = function() {
return type;
};
this.getLog = function() {
return log;
};
};
//Start using visitor
var verifyFile = {
visit : function(file) {
alert("test");
}
};
function test() {
var file = new Entity();
file.accept(verifyFile);
};
test()

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