I have the following JS object in my code:
var myLibrary = {
name: "John",
// Functions
func1: function() {
alert(this.name);
},
func2: function() {
this.func1();
},
// On DOM loaded
onDOMLoaded: function() {
this.func1();
this.func2();
}
}
document.addEventListener('DOMContentLoaded', myLibrary.onDOMLoaded);
When I reference this code using a script tag, I get the following error (in reference to the call in func2
):
Uncaught TypeError: this.func1 is not a function
This is especially weird because if I call the functions from within the DOM, they work perfectly. For example:
<button onclick="myLibrary.func1()">Func 1</button>
<button onclick="myLibrary.func2()">Func 2</button>
Clicking on the buttons does exactly what I want them to. What am I doing wrong here? And how can I fix this issue? Thanks for any help!
A demo can be found here: https://jsfiddle.net/gLxvsze0/