Below is a simple example demonstrating the issue I am facing, which you can also view on JSFiddle here.
While I understand why the issue is happening, I'm unsure of how to resolve it without altering the existing JS structure.
The problem arises when defining prototype functions for JavaScript objects, particularly when there is a nested object at the 2nd level that contains a function calling another function on the parent/root level. This leads to a failure in execution.
In the code snippet provided, the line
this.nestedObject.nested_object_function()
is attempting to invoke the function this.normal_function()
, resulting in the error:
Uncaught TypeError: this.normal_function is not a function
at Object.nested_object_function (VM2493:79)
It seems that the issue stems from this
referencing this.nestedObject
instead of the parent object.
If this assumption is correct, how can I successfully call the desired function from within the nested object function and access a function from the parent object?
I have also experimented with calling JsLibTest.normal_function()
as a test within the
this.nestedObject.nested_object_function()
function, but encountered the same error.
var JsLibTest = (function (document) {
"use strict";
var JsLibTest = function (){
this.init();
};
JsLibTest.prototype = {
init: function() {
this.normal_function();
this.nestedObject.nested_object_function();
},
normal_function: function() {
console.log('this.normal_function() ran');
},
nestedObject: {
nested_object_function: function() {
this.normal_function();
console.log('this.nestedObject.nested_object_function() ran');
},
}
};
return JsLibTest;
})(document);
$(document).ready(function(){
var Sidebar2 = new JsLibTest();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>