JavaScript获取父函数参数

amc*_*dnl 7 javascript

我有一个功能:

define(['module', 'controller'], function(module, controller){
     (new module).build();
});
Run Code Online (Sandbox Code Playgroud)

在内部module.build我想自动获取父类的参数,如:

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

我知道我可以这样做:

module.build.apply(this, arguments);
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更好的方法.有什么想法吗?

mat*_*ttr 8

有一种方法可以做到这一点,在这个例子中说明(http://jsfiddle.net/zqwhmo7j/):

function one(){
  two()
}
function two(){
  console.log(two.caller.arguments)
}
one('dude')
Run Code Online (Sandbox Code Playgroud)

但它不是标准的,可能无法在所有浏览器中使用:

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

你必须改变你的功能:

module = function(){
  this.build = function build(args){
      // make args the arguments from caller ( define ) fn above
    console.log(build.caller.arguments)
  };
};
Run Code Online (Sandbox Code Playgroud)

  • 此外,当使用严格模式(通常建议使用)时,您无法访问调用者,被调用者甚至参数. (2认同)