various-ways-to-invoke-functions-in-dart

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Various Ways to Invoke Functions in Dart

Dart函数的多种调用方式

There are multiple ways to call a Function in Dart.
The examples below will assume the following function:
void myFunction(int a, int b, {int? c, int? d}) {
  print((a, b, c, d));
}
But recently I learned that you can call a functions positional arguments in any order mixed with the named arguments. 🤯
myFunction(1, 2, c: 3, d: 4);
myFunction(1, c: 3, d: 4, 2);
myFunction(c: 3, d: 4, 1, 2);
myFunction(c: 3, 1, 2, d: 4);
In addition you can use the 
.call
operator to invoke the function if you have a reference to it:
myFunction.call(1, 2, c: 3, d: 4);
You can also use 
Function.apply
to dynamically invoke a function with a reference but it should be noted that it will effect js dart complication size and performance:
Function.apply(myFunction, [1, 2], {#c: 3, #d: 4});
All of these methods print the following:
(1, 2, 3, 4)
在Dart中,调用Function有多种方式。
以下示例将基于如下函数展开:
void myFunction(int a, int b, {int? c, int? d}) {
  print((a, b, c, d));
}
不过我最近发现,调用函数时可以将位置参数与命名参数以任意顺序混合使用。 🤯
myFunction(1, 2, c: 3, d: 4);
myFunction(1, c: 3, d: 4, 2);
myFunction(c: 3, d: 4, 1, 2);
myFunction(c: 3, 1, 2, d: 4);
此外,如果你持有函数的引用,还可以使用
.call
运算符来调用它:
myFunction.call(1, 2, c: 3, d: 4);
你也可以使用
Function.apply
通过引用来动态调用函数,但需要注意的是,这会影响Dart转JS后的代码体积和性能:
Function.apply(myFunction, [1, 2], {#c: 3, #d: 4});
所有这些方法都会输出以下内容:
(1, 2, 3, 4)

Demo

演示