[英]How can I create a function which treats a passed parameter as a literal?
I am sure that this has been asked and answered before, but I can't seem to find the right terminology to find an answer.我确信这已经被问过并回答过,但我似乎无法找到正确的术语来找到答案。 I need to dynamically create a series of functions for later use which use certain values defined by parameters upon creation.
我需要动态创建一系列函数以供以后使用,这些函数在创建时使用参数定义的某些值。 For example:
例如:
var i = "bar"; var addBar = function(x) { // needs to always return x + " " + "bar" return x + " " + i; } i = "baz"; var addBaz = function(x) { // needs to always return x + " " + "baz" return x + " " + i; } alert(addBar("foo")); // returns "foo baz" because i = "baz"
Is there a way I can pass i
to these functions so that the original value is used, and not the reference to the variable?有没有办法可以将
i
传递给这些函数,以便使用原始值,而不是对变量的引用? Thank you!谢谢!
You would have to do something that stores the variable.您将不得不做一些存储变量的事情。 Making a function that returns a function is one way to do it.
制作返回 function 的 function 是一种方法。
var i = "bar"; var addBar = (function (i) { return function(x) { return x + " " + i; } }(i)); i = "baz"; var addBaz = (function (i) { return function(x) { return x + " " + i; } }(i)); console.log(addBar("foo")); console.log(addBaz("foo"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.