简体   繁体   English

如何创建将传递的参数视为文字的 function?

[英]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.

相关问题 如何创建一个 function 带有要传递的参数 - How to create a function with a parameter to be passed 是否可以将参数传递给设置为对象文字值的函数? - Can a parameter be passed to a function that is set as an object literal value? 我将一个函数(本身具有一个参数)作为参数传递给另一个函数,以及如何获取该参数 - I passed a function(which itself has a parameter) as a parameter into another function and how to get the parameter 如何根据传递给函数的参数更改变量名? - How can I change a variable name based on a parameter passed to a function? 如何在JavaScript函数中使用传递的参数? - How can I use a passed parameter in a JavaScript function? 如何检查传递给javascript函数的参数值是否为空? - How can I check if the value of a parameter passed to a javascript function is null? 如何调用在另一个函数中作为参数传递的函数 - how to call a function which is passed as parameter in another function 如何在文字中创建动态对象? - How can I create a dynamic object in a literal? 如何在 Class 中的“文字模板”中添加“onclick 函数”? - How can i add an “onclick function” inside a `literal template` which is inside a Class? 如何使用传递给JavaScript函数的输入参数值到此JS函数打开的弹出窗口中? - How can I use the input parameter value passed to a JavaScript function into the popup opened by this JS function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM