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/

5
  • Where in the document are you inserting the script element that references the external library? Commented Jul 15, 2020 at 22:02
  • @ScottMarcus Please check the demo link Commented Jul 15, 2020 at 22:05
  • 1
    That doesn't answer the question I'm asking you. In a Fiddle, you hook up external references differently than you do in actual code. Please just tell us where in the HTML document you've included the script element that references your library. Commented Jul 15, 2020 at 22:06
  • myLibrary.onDOMLoaded.bind(myLibrary) Commented Jul 15, 2020 at 22:08
  • 1
    In HTML event handlers, this refers to the HTML element that received the event Commented Jul 15, 2020 at 22:11

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

1

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

document.addEventListener('DOMContentLoaded',() => { myLibrary.onDOMLoaded(); });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.