0

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/

darkhorse
  • 8,192
  • 21
  • 72
  • 148

2 Answers2

1

You should read about this is JS.

When you call myLibrary.func1() the function will be called with myLibrary context. But when you call just func1 (ie func1 = myLibrary.func1; func1()) this will be called with global Window context.

To solve your problem, you can use bind method, that creates new function linked with provided context:

document.addEventListener('DOMContentLoaded', myLibrary.onDOMLoaded.bind(myLibrary));
Ramil Garipov
  • 465
  • 2
  • 7
1

I think the simplest solution to the context issue is...

document.addEventListener('DOMContentLoaded',() => { myLibrary.onDOMLoaded(); });
user3094755
  • 1,561
  • 16
  • 20