动态绑定参数和缺省值在JavaScript中现有功能 [英] Dynamically bind argument and default value to existing function in Javascript

查看:101
本文介绍了动态绑定参数和缺省值在JavaScript中现有功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设你有一些功能的 someFunc()的已在JavaScript中定义,可能有也可能没有定义自己的参数设置。是否有可能写入另一个函数添加一个必需的参数,并设置参数默认为的 someFunc()的?是这样的:

Let's suppose you have some function someFunc() already defined in javascript, that may or may not have its own argument set defined. Is it possible to write another function to add a required argument and set that argument to a default for someFunc()? Something like:

var someFunc = function(arg1, arg2 ...){ Do stuff...}
var addRequired = function(argName, argValue, fn) { 
    Add the required default arg to a function...
}

addRequired("x", 20, someFunc);

现在someFunc将一个粗略的定义,像这样:

Now someFunc would be defined roughly like so:

someFunc = function(x, arg1, arg2...) {
    x = 20;
    Do stuff...
}

我所真正需要的是到的不仅的绑定的这个的值的函数(我已经知道如何来实现),而且还绑定另一个对象引用该相同的功能(不被称为时间提前,作为用户将定义它,但随后的用户的code的获得在他们自己的功能,用于使用该第二对象的参考的功能)。因此,在我上面的简单的例子,20的价值实际上是一个对象引用。

What I am really seeking is to not only bind a this value to a function (which I already know how to achieve), but also bind another object reference to that same function (the function not being known ahead of time, as a user will define it, but then the user's code has access to this second object reference for use in their own function). So in my simple example above, the "20" value will actually be an object reference.

感谢你能提供任何帮助。

Thanks for any help you can offer.

推荐答案

我相信我找到了答案,但在这个过程中,我才明白,我并不真的需要加一个参数为我的目的,我只是需要参考添加到函数。无论如何,对于达到什么我本来以为我想要的答案的目的,我想出了:

I believe I found an answer, though in the process, I came to realize that I don't really need to add an argument for my purpose, I just need to add the reference into the function. Anyway, for purposes of an answer that achieves what I originally thought I desired, I came up with:

var someFunc = function(arg1,arg2){document.write(x+'<br />'+arg1+'<br />'+arg2)};

var addRequired = function(argName, argValue, fn){
    var funcString = String(fn)
    var paramPattern = new RegExp ('^function\\s*\\([^\\)]*\\b'+argName+'\\b[^\\)]*\\)');
    var alreadyExists= paramPattern.test(funcString);
    if(!alreadyExists) {
       var insertPoint1 = funcString.indexOf('(')+1;
       var insertPoint2 = funcString.indexOf('{')+1;
       var newFunc = funcString.slice(0,insertPoint1)+argName+',' +funcString.slice(insertPoint1, insertPoint2)+argName+' = '+argValue+';' +funcString.slice(insertPoint2);
       return eval('fn = '+newFunc);
    }
}
someFunc = addRequired('x', 20, someFunc);

someFunc(1,2,3);

哪些测试以查看是否精氨酸已经存在,如果没有,则输出:

Which tests to see if the arg already exists, and if not, outputs:

20
2
3

因此​​,它实现了与除所需值的论点。我不知道这是否是实现它的'最好'的方式,但它的工作。

So it achieved the addition of an argument with the value desired. I don't know if this is the 'best' way of achieving it, but it worked.

编辑10年7月9日添加此信息:

我发现上面有一个错误,当我去将它应用到一个不同的情况比我上面的例子(不知现在是什么错误是还记得,那是几个星期前)。我想出了一些没有工作。注意,下面不做任何形式的检查,看是否参数已经存在传递的功能,而事实上,目前预计不带参数本身就是一个函数(我相信这可能是改写以适应带参数,类似于我上面做的)功能。这里是什么我实际使用一个简单的布局:

I found the above had a 'bug' when I went to apply it to a different situation than my example above (I don't recall now what the bug was, that was a few weeks ago). I came up with something that did work. NOTE, the following does not do any kind of check to see if the argument already exists for the function passed in, and in fact, currently it expects a function that DOES NOT TAKE ARGUMENTS ITSELF (I am certain this could be rewritten to accommodate a function with arguments, similar to what I did above). Here is a simple layout of what I actually used:

var addRequired = function(thisObj, func) {
    /*Here I write a string that contains additional functions to add to the 
      passed in function ('func' argument above). In this case, I just show 
      a simple addition function for the example.*/

    var str = 'myAddedFunction = function(x, y) {return x+y}';

    /*Here I am taking the string for that new function I want to add, and 
      appending the old function to it as a string after I have stripped it 
      of its 'function () {' at the beginning and its '}' at the end. NOTE: 
      If I did not care about adding a function, but just arguments, I would 
      have just assigned 'str' the value after the '+' sign below */

    str = str + String(func).replace(/^function\s*\([^\)]*\)[\s\n]*{/, '  ').replace(/}$/, '');

    /*Here I create a new function using the actual new Function declaration so
      I can define my arguments, and using the new string I created that has 
      my new functionality in it along with the user supplied functionality*/

    var newFunc = new Function('myArg1', 'myArg2', str);

    /*Now I return an anonymous function that itself returns the new function 
      with the object that is supposed to be the 'this' of the new function 
      which was passed in as the 'thisObj' argument*/

    return function() {return newFunc.apply(thisObj, arguments)};
}

返回值被分配给原始的功能通过,所以

The return value is assigned to the original passed in function, so:

var userFunc = function() { *do some stuff* }; //representation only
userFunc = addRequired(someObj, userFunc); //overwrite with new functionality

这是什么让我做的是让用户编写一个函数,提前知道,他们将有机会获得我提供(在 myAddedFunction )作为功能还有我自己的职能范围内提供(在 myArg1 myArg2 )的参数。这看起来真的很抽象,如为什么我会永远需要一个,但对于一个项目我的工作,我(和用户)需要它,因为我利用了用户的功能(我的加法)执行某些操作的基于用户关闭我提供的参数。

What this allows me to do is have the user write a function, knowing ahead of time that they will have access to the function I am supplying (the myAddedFunction) as well as the parameters I am supplying (the myArg1, myArg2) within their function. This may seem really abstract, like "why would I ever need that," but for a project I am working on, I (and the user) need it, as I utilize the user's function (with my additions) to perform some operations for the user based off parameters I am supplying.

我忘了提,那我的目的,我不需要,我是要打造成为新的变量(它总是我加入相同的变量)在字符串中传递,但如果我有,我会做了什么像什么在我的帖子,在那里我(可能是一个数组)传递的字符串,使进入参数值的第一部分完成,并用这些来建立我的 newFunc

I forgot to mention, that for my purposes, I did not need to pass in the string that I was going to make into the new variables (it's always the same variables I am adding), but if I had, I would have done something like what was done in the first part of my post, where I passed in (probably an array) of strings to make into the argument values, and used those to build my newFunc with.

这篇关于动态绑定参数和缺省值在JavaScript中现有功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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