-1

I want to recognize the calling function and one function call it that The following example illustrates this issue

<script>
    var func = (function () {
        var check = function (value) {
            //detect caller function
            var that = arguments.callee.caller;

            //I want
            //if Buttom One click --> call print in func1 
            //if Buttom Two click --> call print in func2
        };

        return {
            check:check
        }
    })();

    var func1 = (function () {
        var start = function () {
            func.check(10);
        };
        var print = function (value) {
            alert(value);
        }

        return {
            start: start,
            print: print
        }
    })();

    var func2 ...
</script>
<button id="One" onclick="func1.start()">One</button>
<button id="Two" onclick="func2.start()">Two</button>

Do you have a solution? Many thanks!

  • 1
    `print` is not a property so can't be referenced as a property. Also, don't use `arguments.callee`, give your function a _name_. Yes, function expressions can have names too – Paul S. Sep 08 '15 at 12:53
  • Indeed, [arguments.callee is no longer part of the standard](http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760#235760) and shouldn't be used anymore. As for Function.caller, [it was never standard to begin with](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller). – Domino Sep 08 '15 at 13:00
  • What are you trying to do? –  Sep 12 '15 at 13:38

1 Answers1

0

Putting aside the fact that arguments.callee and Function.caller are both non-standard, the reason why it doesn't work is that you are confusing properties with local variables, all that mixed in with closures.

var func1 = (function () {
    // ...
})();

This creates a function, runs it and saves the result in func1. Since the return statement of your closure is return { start: start }, at the end of this section of code func1 will contain an object which as a method called start.

When you use var, you're only creating a variable which exists inside that function. Outside of the function, it is no longer accessible. You did store the start function in the returned object, but you never returned print so it doesn't exist anymore.

Instead of going line by line and trying to explain all what is wrong, I'll ask you this: what you were actually trying to do? Don't ask us about your attempted solution which didn't work, but about what the code should do.

I suggest you look at these answers I wrote if you need further explanations on closures and scope.

Understanding public/private instance variables

Do the different methods of creating classes in Javascript have names and what are they?

Community
  • 1
  • 1
Domino
  • 6,314
  • 1
  • 32
  • 58