7

I have a function like:

define(['module', 'controller'], function(module, controller){
     (new module).build();
});

inside module.build I want to get the arguments automatically of the parent like:

module = function(){
    this.build = function(args){
        // make args the arguments from caller ( define ) fn above
    };
};

I know I could do something like:

module.build.apply(this, arguments);

but I was wondering if there was a better way. Any thoughts?

axelduch
  • 10,769
  • 2
  • 31
  • 50
amcdnl
  • 8,470
  • 12
  • 63
  • 99
  • I'm not sure I understand your use of `define()`. Can't find it on MDN. Are you using requireJS? If so, could you add that tag? Re: your question, I'd like to know as well. My thoughts are that perhaps there's something to do with creating Classes, but I'm relatively weak on my understanding of all that Classes can do. Maybe along the lines of `module = new myClass; module.define(args); module.build();`? – Phil Tune Nov 06 '14 at 13:51
  • Does the code above work? Because it seems weird to me that you call `module.build()` which is `undefined` since it is the constructor that adds the build method – axelduch Nov 06 '14 at 13:55
  • @aduch whoops, i was prototyping some example code. Fixed now – amcdnl Nov 06 '14 at 14:04
  • @amcdnl I fixed it for you – axelduch Nov 06 '14 at 14:06

1 Answers1

8

There is a way to do this, illustrated in this example (http://jsfiddle.net/zqwhmo7j/):

function one(){
  two()
}
function two(){
  console.log(two.caller.arguments)
}
one('dude')

It is non-standard however and may not work in all browsers:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller

You would have to change your function like so:

module = function(){
  this.build = function build(args){
      // make args the arguments from caller ( define ) fn above
    console.log(build.caller.arguments)
  };
};
mattr
  • 5,458
  • 2
  • 27
  • 22
  • 2
    Also, when using strict mode (which is generally recommended), you can't access caller, callee or even arguments. – axelduch Nov 06 '14 at 14:23
  • After i had the keyword, I found some more references http://stackoverflow.com/questions/280389/how-do-you-find-out-the-caller-function-in-javascript – amcdnl Nov 06 '14 at 14:39