草庐IT

Javascript 代码块作为函数的参数

coder 2025-01-05 原文

鉴于这段代码(我得到的一个 React 组件的简化):

const myFn = function(
  {otherFn = () => {console.log('inside myFn declaration'); return 'true'}}
  ){
      console.log('Inside myFn2 ', otherFn());
      foo(otherFn);
      bar(otherFn);
      ...
}

myFn({name:'some name', type: 'some type'});
// output:
// inside myFn declaration
// Inside myFn2  true

我不明白那里发生了什么。这是什么构造?我指的是“myFn()”中的内容

无论参数是什么,都会调用此构造/代码块(因此它不作为默认参数)

此外,它的目的似乎是在函数的实现中提供“otherFn”,以便它可以作为回调传递给其他函数。

如果目标是让 otherFn 在 myFn 主体内可用,则可以将其实现(以一种可能更容易理解的方式):

const myFn = function(){
  otherFn = () => {console.log('inside myFn declaration'); return 'true'}
  console.log('Inside myFn2 ', otherFn());
  foo(otherFn);
  bar(otherFn);
    ...
  }
}
// Output exactly the same as above

对于这个构造是什么,必须有一个简单的解释,但我似乎无法将它与我所知道的 JavaScript 联系起来。

关于发生了什么的任何提示?

编辑以包括一些答案: 有趣的是,如果我像这样使用这段代码:

function myFn({
  name: 'some name',
  type: 'some type',
  otherFn: () => { console.log("other function"); return false; }
}){
  console.log('here');
} 

它不起作用:-( 使用 chomium 的节点或控制台 为了使其正常工作,“:”应该是“=”,因为它正在分配默认值。

更多编辑。 我选择 Thomas 的答案是因为尽管其他人已经向我暗示了正确的方向(感谢 Benjamin、Ainitak 和所有人),但在阅读 Thomas 的详细解释之前我未能完全“看到”它。

谢谢你们,你们是最棒的!

最佳答案

这结合了两个特点:

参数的默认值:

const fn = (value = 42) => { 
  console.log("value:", value);
}

fn(13);
fn();
.as-console-wrapper{top:0;max-height:100%!important}

wich 基本上是

的简写
const fn = (value) => { 
  if(value === undefined) value = 42;

  console.log("value:", value);
}

并将对象解构作为一个参数

const fn = ({ foo, bar }) => { 
  console.log(foo, bar);
}

fn({ foo: 10, bar: 100 });
fn({ foo: 13 });
fn(window.location);
.as-console-wrapper{top:0;max-height:100%!important}

基本上

const fn = (__arg) => { 
  let foo = __arg.foo;
  let bar = __arg.bar;

  console.log(foo, bar);
}

只是 __arg 只是一个在您的函数中没有实际名称的值。


总结:

const myFn = function({
  otherFn = () => {
      console.log('inside myFn declaration'); 
      return 'true'
    }
  }){
      console.log('Inside myFn2 ', otherFn());
      foo(otherFn);
      bar(otherFn);
      ...
}

只是这两个功能的组合: 参数的对象解构,该参数的默认值恰好是一个函数。

像这样工作:

const myFn = function(__arg){
  let otherFn = __arg.otherFn;
  if(otherFn === undefined){
    otherFn = () => {
      console.log('inside myFn declaration'); 
      return 'true' //why 'true' as a string?
    }
  }

  console.log('Inside myFn2 ', otherFn());
  foo(otherFn);
  bar(otherFn);
  ...
}

What's more, the purpose of it seems to be 'otherFn' being made available inside the implementation of the function so it can be passed as a callback to other functions.

If the goal was to have otherFn available inside myFn body, it could have been implemented (in a maybe easier way to understand)

此构造的目的是为您(使用/调用函数的人)提供将此方法作为配置对象的某些属性注入(inject)函数的能力提供后备/默认,如果您不传递此配置属性。

我觉得这个构造唯一不寻常的地方是这个属性的类型是 function 并且他们选择内联作为默认值的函数。

关于Javascript 代码块作为函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50270085/

有关Javascript 代码块作为函数的参数的更多相关文章

  1. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  2. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  3. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  9. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  10. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

随机推荐