简体   繁体   English

带参数传入的JavaScript获取函数实例

[英]JavaScript Get Function Instance with Arguments Passed In

Say I have the following code. 说我有以下代码。

function myFunc(item) {
    console.log(item);
}

function action() {
    return myFunc("Hello World");
}

const myUncalledFunction = action;
myUncalledFunction(); // will console.log "Hello World"

Is there a way to make this code cleaner? 有没有办法使此代码更清洁? I've looked into .apply() but it looks like that calls the function immediately as well. 我已经研究过.apply()但是看起来它也会立即调用该函数。

The reason I'm wanting to do this is Chai's expect for throw requires you to pass in an uncalled function. 我要执行此操作的原因是Chai的期望抛出要求您传递一个未调用的函数。 But the function I'm wanting to test requires arguments to be passed in. So currently I just created a wrapper function that returns the function with the arguments passed in. 但是我要测试的函数需要传递参数。因此,当前我只创建了一个包装函数,该函数返回带有传递参数的函数。

I feel like there has to be a better way to achieve this that is cleaner and simpler for someone looking at it. 我觉得必须有一种更好的方法来实现这一目标,对于看它的人来说,它更清洁,更简单。

Use .bind to bind arguments (and a calling context, if needed) to a function, which produces a new callable function in the process. 使用.bind将参数(和调用上下文,如果需要)绑定到一个函数,该函数会在该过程中生成一个新的可调用函数。 Here, you can see this as basically allowing you to pass in arguments at one time, and then call the desired function with those arguments later: 在这里,您可以看到这基本上允许您一次传递参数,然后稍后使用这些参数调用所需的函数:

 function myFunc(item) { console.log(item); } const myUncalledFunction = myFunc.bind(undefined, 'Hello World'); myUncalledFunction(); 

Or you might just use a concise arrow function 或者您可能只使用简洁的箭头功能

 function myFunc(item) { console.log(item); } const myUncalledFunction = () => myFunc('Hello World'); myUncalledFunction(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM