I’m new to OOP based JavaScript. For testing purpose I’ve created a following snippet. I’ve created four buttons, on clicking each button it will to different functions. When I click any of the buttons for the first time, it gives the predicted results. on the clicking any of the buttons for the second time, it gives me the following error:
classFunction = new classFunction();
The code which I’ve used is as below:
<html>
<head>
<script type="text/javascript">
var classFunction;
function classFunction() {
this.publicVariable = 'Public Varibale';
var privateVariable = 'Private Variable';
this.publicMethod = function () {
alert('Public Method');
}
function privateMethod() {
alert('private Method');
}
return this;
}
function privateVariable() {
classFunction = new classFunction();
alert(classFunction.privateVariable);
}
function publicvariable() {
classFunction = new classFunction();
alert(classFunction.publicVariable);
}
function privateFunction() {
classFunction = new classFunction();
classFunction.privateMethod();
}
function publicFunction() {
classFunction = new classFunction();
classFunction.publicMethod();
}
</script>
</head>
<body>
<input type="button" value="Private Variable" onclick="privateVariable()" />
<input type="button" value="Public Variable" onclick="publicvariable()" />
<input type="button" value="Private Function" onclick="privateFunction()" />
<input type="button" value="Public Function" onclick="publicFunction()" />
</body>
</html>
Is there are any reason that the new operator will not be working for the second time?
The reason is because your variable name and constructor name are same. So, the first time when you create a new instance and assign it to variable, class gets overwritten with instance.
Ensure you name the below differently.