访问外部调用程序函数的参数 [英] accessing outer caller function arguments

查看:139
本文介绍了访问外部调用程序函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,函数和一些其他的对象作为参数,使得这些参数作为函数的默认参数,并返回一个新的功能。

I want to write a function that takes a function and some other objects as arguments and makes these arguments as default arguments for the function and returns a new function.

假设我们有drawRect中(X,Y,X2,Y2)我想写一个名为部分功能,使

assume we have drawRect(x, y, x2, y2) I want to write a function named 'partial' so that

(partial(drawRect, 0, 0))(x2, y2);

等于

drawRect(0, 0, x2, y2);

请注意,我要的功能部分必须灵活,需要任何功能,任何数量的参数。

please note that I want to function partial be flexible so it takes any function and any number of arguments.

到目前为止,我已经写了这一点:

so far I've written this:

function temp(a, b, c, d){
  document.write(a + b + c + d);
}

function partial(func){
  var arr = new Array();
  for (var i = 0; i<arguments.length; i++){
    arr.push(arguments[i+1]);
  }

  var tf = function(){f.apply(this, arr.concat(func.arguments))}
  console.log(2);
  return tf;
}

var ff = partial(temp, 44, 55);
ff(20, 30); 

但文件上写了一个南。我需要打电话的时候访问功能'FF'论点,但我不知道该怎么做。
你们可以帮我解决这个?

but it writes a 'Nan' on document. I need to access to function 'ff' arguments when calling but I've no idea how to do it. Can you guys please help me solving this?

推荐答案

似乎有很多unncessary测试code在那里,我已经清理。我的理解,下面和的code此演示你需要什么。

There seemed to be a lot of unncessary testing code in there, which I've cleaned up. To my understanding, the code below and this demo do what you required.

function temp(a, b, c, d){
  console.log(a + b + c + d);
}

function partial(f){
    var defaultArgs = Array.prototype.slice.call(arguments, 1);
    var that = this;

    var tf = function(){
        f.apply(that, defaultArgs.concat(Array.prototype.slice.call(arguments)));
    }
    return tf;
}

var ff = partial(temp, 44, 55);
ff(20, 30);

// console output: 149

这篇关于访问外部调用程序函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆