0

I have a javascript file and i'm using closure to create functions:

  "use strict";
  (function(window) {
var ele = function() {

    return {
      func3:function(methodToCall){
       methodToCall();
          },
        func1:function() {
            this.func2();
        },
        func2:function() {

        }
    }
}
window.ele = new ele();
})(window);

As you can see, i'm trying to call func2 from inside func1. The browser barks at me saying "func2 is undefined". I'm calling func1 like so:

  <script>
              ele.func3(ele.func1());

   </script>

How do i call func2 from func1? Thanks

BoundForGlory
  • 4,114
  • 15
  • 54
  • 81

2 Answers2

0

When you do methodToCall(), its the same as window.methodToCall(). So when func1 runs, this refers to the window object instead of what you really want. One way of fixing it is binding the scope manually like this:

methodToCall.bind(this)();

That way, the this reference will be passed to func1 instead of window and it will work

juvian
  • 15,875
  • 2
  • 37
  • 38
0

Did you ever get this working? It's a matter of scope and closures. You can get lots of good detail about using closures here: https://stackoverflow.com/a/111111/6441528

In addition, here's a short piece of code that should answer your question directly by description:

    function ClosureObject() {

        var _this = this;

        this.interior1 = function() {
            console.log('** in interior 1');
            var callingOtherFunction = _this.interior2();
            console.log('** return from other function in closure', callingOtherFunction);
        }

        this.interior2 = function() {
            return "returning from interior2";
        }

    }

Basically, by declaring the scope locally within your function using 'this', you can access other functions within the closure. This should allow you to do something like:

var foo = new ClosureObject();
foo.interior1();

That would output ** return from other function in closure returning from interior2 into your console.

Community
  • 1
  • 1
hightempo
  • 469
  • 2
  • 8