0

I was trying to modularise the JS code but stuck at a point for quite a long time, I know the solution will be easy but just can't figure it out. Here is the fiddle link: Fiddle.

Adding code here as well.

window.a = (function () {
  function abc() {
    alert("Hi");
  }
  return {
    abc: abc
  }
});


window.b = (function (aWindow) {
  function i() {
    aWindow.abc();
  }
  return {
    i: i
  }
})(window.a);
<a href="#" class="abc" onClick="window.b.i()">Click Me</a>

Error

"<a class='gotoLine' href='#60:10'>60:10</a> Uncaught TypeError: aWindow.abc is not a function"
1
  • 1
    you're missing () for the first IIFE - i.e. otherwise it's NOT an IIFE and window.a is just that function as you've written it - either that or do })(window.a()) Commented Oct 14, 2020 at 3:52

3 Answers 3

2

You need to call window.a to obtain an object from its prototype.


window.b = (function(aWindow) {

  function i() {
    aWindow.abc();
  }

  return {
    i: i
  }

})(window.a()); //Call Window.a
Sign up to request clarification or add additional context in comments.

Comments

2

You missed () when calling aWindow. This snippet works well.

window.a = (function () {
  function abc() {
    alert("Hi");
  }
  return {
    abc: abc
  }
});


window.b = (function (aWindow) {
  function i() {
    aWindow().abc();
  }
  return {
    i: i
  }
})(window.a);
<a href="#" class="abc" onClick="window.b.i()">Click Me</a>

Comments

1

You have missed () on window.a definition so it's not executed.

window.a = (function () {
  function abc() {
    alert("Hi");
  }
  return {
    abc: abc
  }
})();

window.b = (function (aWindow) {
  function i() {
    console.log(aWindow);
    window.a.abc();
  }
  return {
    i: i
  }
})(window.a);
<a href="#" class="abc" onClick="window.b.i()">Click Me</a>

2 Comments

I knew it was something small but could not figure it out any reference to read this concept and clear it out in-depth once for all. Thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.