简体   繁体   English

Javascript代码块作为函数的参数

[英]Javascript code block as a parameter for a function

Given this piece of code (simplification of a React component I came by): 鉴于这段代码(我简化了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

I don't understand what is going on there. 我不明白那里发生了什么。 What's this construct? 这个结构是什么? I'm referring to what is inside 'myFn()' 我指的是'myFn()'里面的内容

This construct/code-block is being called no matter what argument (therefore it doesn't behave as a default parameter) 无论什么参数,都会调用此构造/代码块(因此它不会作为默认参数)

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. 更重要的是,它的目的似乎是'otherFn'在函数的实现中可用,因此它可以作为回调传递给其他函数。

If the goal was to have otherFn available inside myFn body, it could have been implemented (in a maybe easier way to understand) as: 如果目标是在myFn体内提供otherFn,那么它可以实现(以一种更容易理解的方式):

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

There has to be a simple explanation of what this construct is, but I don't seem to be able to connect it with anything I know of JavaScript. 必须有一个简单的解释,这个构造是什么,但我似乎无法将它与我所知道的任何JavaScript连接。

Any hints on what's going on? 有关正在发生的事情的任何提示?

EDIT to include some of the answers: Interestingly, if I use this code like: 编辑包括一些答案:有趣的是,如果我使用这样的代码:

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

it does not work :-( using either node or console of chomium In order for it to work, the ':' should be '=' because it is assigning default values. 它不起作用:-(使用chomium的节点或控制台为了使它工作,':'应该是'=',因为它正在分配默认值。

More EDIT. 更多编辑。 I've chosen Thomas' answer because although others have hinted me in the right direction (thanks Benjamin, Ainitak and all) I failed to fully 'see' it until I read Thomas' detailed explanation. 我选择了托马斯的答案,因为虽然其他人已经向我暗示正确的方向(感谢本杰明,艾尼塔克和所有人),但在我阅读托马斯的详细解释之前,我没有完全“看到”它。

Thank you guys you're the best! 谢谢你们,你们是最棒的!

This combines two features: 这结合了两个功能:

default value for an argument: 参数的默认值:

 const fn = (value = 42) => { console.log("value:", value); } fn(13); fn(); 
 .as-console-wrapper{top:0;max-height:100%!important} 

wich is basically a shorthand for 这基本上是一个简写

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

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

And object destructuring as an agument 并将对象解构为一个文章

 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} 

basically 基本上

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

  console.log(foo, bar);
}

Just that __arg is just a value that doesn't have an actual name inside your function. 只是__arg只是一个在函数中没有实际名称的值。


Summary: 摘要:

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

is just the combination of these two features: Object destructuring of an argument with a default value for that argument that just happens to be a function. 只是这两个特征的组合:参数的对象解构与该参数的默认值恰好是一个函数。

Works like this: 像这样工作:

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. 更重要的是,它的目的似乎是'otherFn'在函数的实现中可用,因此它可以作为回调传递给其他函数。

If the goal was to have otherFn available inside myFn body, it could have been implemented (in a maybe easier way to understand) 如果我们的目标是在myFn体内提供otherFn,那么它可以实现(可能更容易理解)

The purpose of this construct is to provide you (who uses/calls the function) with the ability to inject this method into the function as some property of the configuration object and provide a fallback/default, if you don't pass this config property. 此构造的目的是为您(使用/调用函数)提供将此方法作为配置对象的某些属性注入函数的能力, 提供回退/默认值,如果您不传递此配置属性。

Imo the only uncommon thing about this construct is that the type of this property is function and that they have chosen to inline the function that serves as the default value. Imo关于这个结构的唯一不常见的事情是这个属性的类型是function ,并且他们选择内联作为默认值的函数。

It's object destructuring syntax for the function parameter, with an arrow function as the default initialiser for the otherFn property. 它是函数参数的对象解构语法,使用箭头函数作为otherFn属性的默认初始化函数。

You can use it like 你可以像使用它一样

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

I finally understood 'what is the construct there'. 我终于明白了“那里的建筑是什么”。 It is 2 things simultaneously: 同时是两件事:

  • object deconstruction 对象解构
  • default parameter values for the one deconstructed part 一个解构部分的默认参数值

Of course I know what each of these are, but the fact that the only part of the object being deconstructed was a function, which in turn was being provided with a default inline implementation got me all but confused all the time. 当然我知道每个都是什么,但事实是被解构的对象的唯一部分是一个函数,而这个函数反过来被提供了一个默认的内联实现,让我一直都很困惑。

Also, I was at a loss of understanding why the implementation was done this way instead of some more readable way (eg inside the body of the function). 此外,我无法理解为什么实现是以这种方式完成而不是一些更易读的方式(例如在函数体内)。 As Thomas suggests, now I understand that that is a way for the caller of the function to provide an implementation for the inner function (which has a default implementation 'just in case'). 正如Thomas建议的那样,现在我明白这是函数调用者为内部函数提供实现的一种方式(它具有默认实现'以防万一')。

It has had me thinking a while, but it is nice when you get to finally understand it. 它让我思考了一段时间,但是当你最终理解它时它很好。 Thank you all! 谢谢你们!

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

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