1

This is a general programming question, not specific to this code example.

How do I detect whether a particular method was called or not from within a function?

Imagine you want to be able to tell whether a particular method was called so that you can change what you return based on that.

var turtle = function() {
    var vars = {
        name: "Shelly",
        age: 103
    };

    this.actions = function() {
        var methods = {
            crawl: function() {
                //etc...
            },
            mutate: function() {
                //etc...
            },
            eat: function() {
                //etc...
            }
        };

      if (methodWasCalled) { // <- The part I don't know how to do
          return methods;
      } else {
          return this;
      }
        
    };
    if (methodWasCalled) { // <- The part I don't know how to do
        return vars;
    } else {
        return this;
    }
};

Based on the above example, someone could use: turtle() and get access to the 'vars' object, or they could use: turtle().mutate() and the turtle object would execute the block inside that function.

2
  • why would you need to code in this manner? I imagine there's a better way so what is your use case Commented Jul 24, 2014 at 18:34
  • unfortunately, I can't talk about the specific use case, but if we use the turtle analogy what might you do differently? what about the example given seems inefficient or not as 'good'? Commented Jul 24, 2014 at 20:24

1 Answer 1

1

To get the caller access the arguments object.

alert("caller is " + arguments.callee.caller.toString());

Callee refers to the function being executed, in your case mutate. It has a property that references the caller.

Best thing for you to do is break out a debugging kit (I personally prefer Chrome/IE) and explore the object to see the full details of info you want to see.

Sign up to request clarification or add additional context in comments.

Comments

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.