Recently, I want to expand my skills. I feel that Flutter is quite eager, so I got in. But to use Flutter, you must first learn Dart. After a cursory look, Dart is similar to JS in terms of design: event-driven, single-threaded environment, familiar keywordsvar
/const
Now that I have learned JS, and from digging in common both languages and into related differences start might be a good learning program, you can also take the opportunity to review the JS.
Of course, this series of articles are more self-study insights. Omissions and fallacies are unavoidable. If you know the worms, please feel free to correct me.
Unless otherwise specified, the JS in this article includes all the features from ES5 to ES2021.
1. Ordinary functions
Similarities
The function structure is similar: first is the function declaration keyword (here is slightly different, as will be
()
later), followed by the function name, and then the parameter list is wrapped in parentheses 06161031b39a34, separated by comma,
, and finally is wrapped in{}
The body of the function:> // JavaScript | // Dart > function foo(){ | int foo() { > // do some thing here | // do some thing here > } | }
;
- Use
=
to specify default values for function parameters; JS can use an object as a parameter to specify certain values of the object. Dart also supports a similar syntax, but limited to the optional parameter .
> // JavaScript | // Dart > function foo(a = 1, b = 2){ | int foo([a = 1, b = 2]){ > return a + b; | return a + b; > } | }
the difference
Different declaration keywords
- Ordinary functions in JS must be
function
keyword 06161031b39b2e; Ordinary functions in Dart start with a type declaration, which can also be defaulted.
> // JS: starts with `function` | // Dart 可缺省返回类型 > function foo(a = 1, b = 2){ | /*int*/ foo(a = 1, b = 2){ > return a + b; | return a + b; > } | }
JS does not support type declaration
- JS does not support type declarations, so the return value and parameter types will only be determined at runtime;
Dart supports type declarations, you can specify the return value and the type of parameters, but both can be defaulted.
> // JS | // Dart > function foo(a = 1, b = 2){ | int foo(int a, int b){ > return a + b; | return a + b; > } | }
Optional parameters
- All the parameters of JS (except for the object as a named parameter carrier and the positional parameters in front) are optional parameters;
The Dart function can use a
[]
wrap the optional parameter at the end of its parameter list. All named parameters that arerequired
// Dart 位置参数 foo(int a, [int b = 2]){ return a + b; } // Dart 命名参数 foo({required a, b = 2}){ return a + b; }
How to pass in named parameters
As mentioned earlier, JS's named parameters actually use object space, so when calling a function, you can directly pass in an object at the corresponding position:
function testFunc(a, {b = 1}){ return a + b; } testFunc(a, {b: 2}); // 3 testFunc(a); // 会报错,因为第二个位置参数必须是一个对象
;
Dart's named parameter is a specific syntax, which is specified
name: value
int testFunc(a, {b = 1}){ return a + b; } testFunc(a, b : 2); // 3
。
In contrast, Dart's grammar can be concise and precise, but it is somewhat unaccustomed to the first sight.
other
- In an example, I seem to have caught a glimpse of
foo.call
. It seems that some of the "essence" of JS has also been borrowed by Dart. I don't know how similar the two are; - There is no concept of variable parameters in JS, but you can use
arguments
or[...args]
access all the parameters of the function. This isHOC
) in development, but I haven’t seen a similar Dart syntax or method yet. Know how to use Dart to obtain parameter lists of unknown length; - The similarities and differences of the anonymous functions in the two languages are basically the same as the named functions.
- When it comes to JS, you have to say that the "fascinating"
this
points to, luckily Dart's ordinary functions don't have this thing! JS named functions can be assigned to a variable at the same time they are declared, but in Dart you can only do this for anonymous functions:
> JS | // Dart 把注释去掉,将无法通过编译 > var foo = function fooName (){ | var foo = /*fooName*/ (){ > // do some thing | // do some thing > } | }; > | //↑ 注意!赋值语句后的分号不可或缺
。
2. Arrow functions (called "arrow expressions" in Dart)
Similarities
The syntax of both is
(parameter list) => expression;
> // JS | // Dart > let foo = (a) => a++; | var foo = (a) => a++;
the difference
Parentheses cannot be omitted
- For the arrow function of JS, if there is only one parameter, there is no need to set parentheses outside the parameter list;
Dart's arrow functions must enclose the parameter list in parentheses.
> // JS | // Dart > var foo = a => a++; | var foo = (a) => a++;
Dart arrow expression can only write one expression
Strictly speaking, both of them can only write one expression, but {}
in the two languages are different, which shows that the expressive power of JS arrow functions is a bit stronger.
- In JS, the curly braces after the fat arrow are the same as the curly braces of ordinary functions. They represent the function body, which contains a code block. If there is a return value, it needs to be at the end of
return
; But in Dart, the curly braces after the fat arrow are
Set
orMap
. The addition of curly braces means that the return value of the function becomes an instance ofSet
orMap
> // JS | // Dart:return 你就错了 > var foo = (a) => {return a++}; | var foo = (a) => {/*return*/ a++}; > console.log(`res: ${foo(2)}`); | print(`res: ${foo(2)}`)); > // res: 3 | // res: {3} // 返回的是一个 Set
, If you are not comfortable with Dart's processing method, think about
[]
. In addition, there are people who want to return an object like this:var foo = a => { a: a }; // 当然是不可能的,这会被识别成 label 语法,而非对象
, It can't be done in JS, now Dart can help you realize it: this kind of syntax will return an instance of
Map
But if you want to put more statements in the arrow function, you can wrap it
IIFE
var testFunc = (start, {end = 7}) => (() { var finalEnd = start + end; for(num i = start; i < finalEnd; i++){ display((i + 1).toString()); } })();
, Uh... people can't help but think of a classic ES5 interview question.
If I force myself to add parentheses-
var foo = (a) => ({'a': a});
The form of JS and Dart are very similar, the former returns an object, and the latter returns
Map
.Or, the following code
var fun = (a) => [a];
The performance in the two languages is highly consistent: JS returns Array; Dart returns List.
3. Dart's main function
- As we all know, JS has no entry function. In the current execution context, "naked" expressions will be executed directly, and the top-level scope of JS is also the first execution context.
But Dart doesn't prevent you from writing expressions in the global scope-provided that they are written in variable declaration statements:
void main(){ // invoke functions } var a = 3 + 2 - 5 * 0;
; Dart does not prevent you from calling functions globally-but this statement may be optimized at compile time:
void main(){ // invoke functions } testFunc(){ print('called me'); } var testVar = testFunc(); // 控制台空空如也
(Of course this may be a feature of the web version of DartPad. Other syntax checkers/compilers may report errors. It is better to do less sao operations outside of the specification).
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。