You need to make ShowCount()
accessible from outside the constructor function. You can do this by attaching the function to a ShowCount
property of the returned instance. You then would need to call mySingleton.ShowCount()
:
var mySingleton = new function()
{
this.count = 123;
document.write("<div onclick='mySingleton.ShowCount();'>Click</div>");
this.ShowCount = function() {
alert(this.count);
};
}();
Remark: This is just to demonstrate how to fix your implementation, but as already pointed out in the comments above, it is not good style.
A better implementation would create the element and attach its event handlers using the DOM API while avoiding document.write()
. Also, your singleton is actually none, so better rename it to something else to avoid confusion (or implement a real singleton):
function myClass() {
this.count = 123;
// Create <div> and attach onclick handler:
let div = document.createElement('div');
div.textContent = 'Click';
div.onclick = () => alert(this.count);
document.body.appendChild(div);
};
let instance = new myClass();
Depending on your use-case, it might still be unusual to have a constructor function create DOM elements.