简体   繁体   English

将参数传递给回调函数的正确方法是什么?

[英]What is the right way to pass parameters into callback functions?

It's a working example.这是一个工作示例。 As you can see I'm calling setElemHeight function with a returned value from getElemHeight .正如你可以看到我打电话setElemHeight函数从返回的值getElemHeight But i think it's a bad practice to pass value instead of function.但我认为传递值而不是函数是一种不好的做法。

Option 1) I can wrap it in anonymous function like this:选项 1)我可以将它包装在匿名函数中,如下所示:

function () { getElemHeight('.map-svg') }

Option 2) I can call it inside setElemHeight function and pass parameter there, but i think it would ruin Open Closed Principle.选项 2)我可以在setElemHeight函数中调用它并在setElemHeight传递参数,但我认为它会破坏开放封闭原则。

My question is: What is the right way to pass parameters into callback functions?我的问题是:将参数传递给回调函数的正确方法是什么?

Thanks.谢谢。

function(elem) {
  return $(elem).height()
}

function setElemHeight(elem, callback, offset) {
  let elemHeight = callback
  $(elem).height(elemHeight - offset)
}
$(window).on('load resize', function() {
  setElemHeight('#dealersTabContent', getElemHeight('.map-svg'), 190)
})

Passing a value to a function is just fine, unless the height of the element changes over time.将值传递给函数就可以了,除非元素的高度随时间发生变化。

If it changes, you'll want to re-calculate the height on each call of the event handler.如果它发生变化,您将需要在每次调用事件处理程序时重新计算高度。 If it does not, you can just pass the value in, since it will always use the same value anyway.如果没有,您可以只传入该值,因为无论如何它将始终使用相同的值。

Also, this line:此外,这一行:

 let elemHeight = callback

If callback is a function, this doesn't actually invoke the callback, it just assigns the function to a new variable.如果callback是一个函数,这实际上不会调用回调,它只是将函数分配给一个新变量。
If you want elemHeight to get the return value, you'll need to do this instead:如果您希望elemHeight获得返回值,则需要这样做:

 let elemHeight = callback() // <== Notice the parenthesis

If it's a value, you probably want to change the name.如果它是一个值,您可能想要更改名称。

As for the Open Closed principle, I think that in JS, being a dynamic, weakly typed language, this will probably mostly apply to modules and not a specific code snippet.至于开放封闭原则,我认为在 JS 中,作为一种动态的弱类型语言,这可能主要适用于模块而不是特定的代码片段。 There are some tricks for creating encapsulation in JS and for allowing extension only in certain places, but generally you can plug anything you want anywhere, so I just don't worry about it.在 JS 中创建封装和只允许在某些地方扩展有一些技巧,但通常你可以在任何地方插入任何你想要的东西,所以我不担心它。

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

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