gpt4 book ai didi

javascript - 有没有办法以编程方式向函数添加新参数?

转载 作者:行者123 更新时间:2023-11-30 17:30:06 26 4
gpt4 key购买 nike

因为我可以通过调用函数的 Function.length 属性来确定函数期望的参数数量,我有什么方法可以通过编程创建正确数量的参数以插入该函数在运行时?示例:

var xyz = function(a,b) {};
var bcd = function(a,b,c,d,e,f) { }; // vararg example
var doc = document, func_length = xyz.length;
doc.xyz = (function() {

return function(a,b,c,d,e) { /* works for one but not the other */ } }).call(doc);

/* would prefer to `return function(a,b)` with only 2 parameters, if it is
used for function `xyz` (though returning 5 works fine in this case), and to
`return function(a,b,c,d,e,f)` with 6 if used for function `bcd` (which does
not work with only five params). */

// thinking about xyz.apply(null,arguments)...but which arguments..? :(

// Returning function(a,b,c,d,e) does not support functions with more than five
// parameters...which would mostly be varargs - hence my question

// I am also well aware that I can use an object or an array instead of
// using many params.

/* This is for incorporating a user-defined function for use in my code, while
* allowing for my function to do 'other stuff' afterward. (And allowing for
* varargs, of course).
* Because coding something like: doc.xyz = xyz is inflexible */

如您所见,我不知道该怎么做,甚至不知道是否可行。搜索栏没有给我任何其他类似的问题,否则我不会问...

最佳答案

NOTE: This answer is a product of misunderstanding but
may help the future visitors of this site.

另一种方式:

你真的需要添加参数吗?以这种方式编写函数就足够了:

function foo(){ //No arguments predefined
a = arguments[0] || ""; //first argument or (if not defined) empty string
b = arguments[1] || ""; //second argument etc.
c = arguments[2] || ""; //third argument etc.
alert(a+b+c);
}
foo("Hello ", "world!");

这会提示“Hello world”。



您想要的解决方案:

最简单的方法:

这是你要求的,但它不像以前的解决方案那么简单。
您可以定义一个包含所有参数的函数和一个随时间变化的处理函数

(function(){ //Wrapper

var foo_meta = function(a,b,c,d){ //Local meta of foo
alert(a+b+c+d); //Do the code
};

window.foo = function(a,b){ //Global foo
return foo_meta(a,b,"","");
};

window.redefine_foo = function(){ //Global foo-changer
//Rewrites foo
window.foo = function(a,b,c){
return foo_meta(a,b,c,"");
};
};

})(); //Wrapper

//Do some code
foo("a","b");

redefine_foo(); //Rewrite foo

foo("a","b","c");

//Note that foo_meta is not defined here
foo_meta == undefined; //It's safe in the wrapper :)

这将提醒“ab”,然后是“abc”。 wrapper function的含义见引用资料。



引用:

参数数组:http://goo.gl/FaLM1H
包装码:http://goo.gl/uQ5sd0

关于javascript - 有没有办法以编程方式向函数添加新参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23307326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com