将参数和默认值动态绑定到 Javascript 中的现有函数 [英] Dynamically bind argument and default value to existing function in Javascript

查看:25
本文介绍了将参数和默认值动态绑定到 Javascript 中的现有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您已经在 javascript 中定义了一些函数 someFunc(),它可能有也可能没有定义自己的参数集.是否可以编写另一个函数来添加必需的参数并将该参数设置为 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...
}

我真正想要的是不仅将一个this值绑定到一个函数(我已经知道如何实现),而且还绑定另一个对象引用到相同的函数(该函数不被提前知道,因为用户将定义它,但随后用户的代码可以访问第二个对象引用以在他们自己的函数中使用).所以在我上面的简单例子中,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);

哪个测试以查看 arg 是否已经存在,如果不存在,则输出:

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.

编辑 7/9/10 以添加此信息:

当我将上面的内容应用于与上面的示例不同的情况时,我发现上面有一个错误"(我现在不记得错误是什么,那是几周前的事).我想出了一些确实有效的方法.注意,下面没有做任何类型的检查来查看传入函数的参数是否已经存在,事实上,目前它期望一个不采用参数本身的函数(我确信这可以被重写以适应一个带参数的函数,类似于我上面所做的).这是我实际使用的简单布局:

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天全站免登陆