Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript get parent function arguments

Tags:

javascript

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?

like image 812
amcdnl Avatar asked Nov 06 '14 13:11

amcdnl


People also ask

What is argument objects in JavaScript& how to get the type of arguments passed to a function?

The arguments object is a local variable available within all non-arrow functions. You can refer to a function's arguments inside that function by using its arguments object. It has entries for each argument the function was called with, with the first entry's index at 0 .

Which keyword is used to access the array of arguments of a function in JavaScript?

It's a native JavaScript object. You can access specific arguments by calling their index. var add = function (num1, num2) { // returns the value of `num1` console.

What is args in JavaScript?

args is a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters. It's basically the replacement for the arguments object. Instead of writing function max() { var values = Array. prototype.

Which keyword is used to call the base parent class functions from the child functions in JavaScript?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.


1 Answers

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)
  };
};
like image 131
mattr Avatar answered Nov 07 '22 11:11

mattr