en
This commit is contained in:
parent
547854a151
commit
6fd7a2f7f3
2 changed files with 111 additions and 136 deletions
|
@ -1,64 +1,8 @@
|
|||
# Function expressions
|
||||
|
||||
In JavaScript a function is a value. Just like a string or a number.
|
||||
Function Expression is analternative syntax for creating a function.
|
||||
|
||||
Let's output it using `alert`:
|
||||
|
||||
```js
|
||||
//+ run
|
||||
function sayHi() {
|
||||
alert( "Hello" );
|
||||
}
|
||||
|
||||
*!*
|
||||
alert( sayHi ); // shows the function code
|
||||
*/!*
|
||||
```
|
||||
|
||||
Note that there are no brackets after `sayHi` in the last line. The function is not called there.
|
||||
|
||||
The code above only shows the string representation of the function, that is it's source code.
|
||||
|
||||
[cut]
|
||||
|
||||
|
||||
As the function is a value, we can copy it to another variable:
|
||||
|
||||
```js
|
||||
//+ run no-beautify
|
||||
function sayHi() { // (1)
|
||||
alert( "Hello" );
|
||||
}
|
||||
|
||||
let func = sayHi; // (2)
|
||||
func(); // Hello // (3)
|
||||
|
||||
sayHi = null; // (4)
|
||||
sayHi(); // error
|
||||
```
|
||||
|
||||
<ol>
|
||||
<li>Function declaration `(1)` creates the function and puts it into the variable `sayHi`"</li>
|
||||
<li>Line `(2)` copies it into variable `func`.
|
||||
|
||||
Please note again: there are no brackets after `sayHi`. If they were, then the call `let func = sayHi()` would write a *result* of `sayHi()` into `func`, not the function itself.</li>
|
||||
<li>At the moment `(3)` the function can be called both as `sayHi()` and `func()`.</li>
|
||||
<li>...We can overwrite `sayHi` easily. As well as `func`, they are normal variables. Naturally, the call attempt would fail in the case `(4)`.</li>
|
||||
</ol>
|
||||
|
||||
[smart header="A function is an \"action value\""]
|
||||
Regular values like strings or numbers represent the *data*.
|
||||
|
||||
A function can be perceived as an *action*.
|
||||
|
||||
A function declaration creates that action and puts it into a variable of the given name. Then we can run it via brackets `()` or copy into another variable.
|
||||
[/smart]
|
||||
|
||||
## Function Expression [#function-expression]
|
||||
|
||||
There is an alternative syntax for creating a function. It much more clearly shows that a function is just a kind of a value.
|
||||
|
||||
It is called "Function Expression" and looks like this:
|
||||
It looks like this:
|
||||
|
||||
```js
|
||||
//+ run
|
||||
|
@ -86,6 +30,81 @@ function sayHi(person) {
|
|||
}
|
||||
```
|
||||
|
||||
## Function is a value
|
||||
|
||||
Function Expressions clearly demonstrate one simple thing.
|
||||
|
||||
**In JavaScript, function is a kind of a value.**
|
||||
|
||||
We can declare it as we did before:
|
||||
|
||||
```js
|
||||
function sayHi() {
|
||||
alert( "Hello" );
|
||||
}
|
||||
```
|
||||
|
||||
...Or as a function expression:
|
||||
|
||||
```js
|
||||
let sayHi = function() {
|
||||
alert( "Hello" );
|
||||
}
|
||||
```
|
||||
|
||||
The meaning of these lines is the same: create a function, put it into the variable `sayHi`.
|
||||
|
||||
Yes, no matter, how it is defined -- it's just a value.
|
||||
|
||||
We can even show it using `alert`:
|
||||
|
||||
```js
|
||||
//+ run
|
||||
function sayHi() {
|
||||
alert( "Hello" );
|
||||
}
|
||||
|
||||
*!*
|
||||
alert( sayHi ); // shows the function code
|
||||
*/!*
|
||||
```
|
||||
|
||||
Note that there are no brackets after `sayHi` in the last line. The function is not called there. Instead the `alert` shows it's string representation, that is the source code.
|
||||
|
||||
As the function is a value, we can also copy it to another variable:
|
||||
|
||||
```js
|
||||
//+ run no-beautify
|
||||
function sayHi() { // (1) create
|
||||
alert( "Hello" );
|
||||
}
|
||||
|
||||
let func = sayHi; // (2) copy
|
||||
func(); // Hello // (3) callable!
|
||||
|
||||
sayHi = null; // (4) kill old
|
||||
sayHi(); // error! (null now)
|
||||
```
|
||||
|
||||
<ol>
|
||||
<li>Function declaration `(1)` creates the function and puts it into the variable `sayHi`"</li>
|
||||
<li>Line `(2)` copies it into variable `func`.
|
||||
|
||||
Please note again: there are no brackets after `sayHi`. If they were, then the call `let func = sayHi()` would write a *result* of `sayHi()` into `func`, not the function itself.</li>
|
||||
<li>At the moment `(3)` the function can be called both as `sayHi()` and `func()`.</li>
|
||||
<li>...We can overwrite `sayHi` easily. As well as `func`, they are normal variables. Naturally, the call attempt would fail in the case `(4)`.</li>
|
||||
</ol>
|
||||
|
||||
Again, it does not matter how to create a function here. If we change the first line above into a Function Expression: `let sayHi = function() {`, everything would be the same.
|
||||
|
||||
[smart header="A function is a value representing an \"action\""]
|
||||
Regular values like strings or numbers represent the *data*.
|
||||
|
||||
A function can be perceived as an *action*.
|
||||
|
||||
We can copy it between variables and run when we want.
|
||||
[/smart]
|
||||
|
||||
|
||||
## Comparison with Function Declaration
|
||||
|
||||
|
@ -93,7 +112,7 @@ The "classic" syntax of the function that looks like `function name(params) {...
|
|||
|
||||
We can formulate the following distinction:
|
||||
<ul>
|
||||
<li>*Function Declaration* -- is a function, declared as a separate code statement.
|
||||
<li>*Function Declaration* -- is a function, declared as a separate statement.
|
||||
|
||||
```js
|
||||
// Function Declaration
|
||||
|
@ -103,24 +122,29 @@ function sum(a, b) {
|
|||
```
|
||||
|
||||
</li>
|
||||
<li>*Function Expression* -- is a function, created in the context of an another expression, for example, an assignment.
|
||||
<li>*Function Expression* -- is a function, created anywhere inside an expression.
|
||||
|
||||
Here the function is created to the right side of an assignment:
|
||||
```js
|
||||
// Function Expression
|
||||
let sum = function(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
```
|
||||
Soon we're going to see more use cases.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
The main difference between them is the creation time.
|
||||
|
||||
**Function Declarations are processed before the code begins to execute.**
|
||||
<ul>
|
||||
<li>Function Declarations are processed before the code begins to execute.</li>
|
||||
<li>Function Expressions are created when the execution reaches them.</li>
|
||||
</ul>
|
||||
|
||||
In other words, when JavaScript prepares to run the code block, it looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". Then it runs the code.
|
||||
In other words, when JavaScript prepares to run the code block, it looks for Function Declarations in it and creates the functions. We can think of it as an "initialization stage". Then it runs the code. And while the code is running, Function Expressions can be created.
|
||||
|
||||
As a side-effect, functions declared as Function Declaration can be called before they are defined.
|
||||
As a side-effect, functions declared as Function Declaration can be called earlier than they are defined.
|
||||
|
||||
For instance, this works:
|
||||
|
||||
|
@ -148,17 +172,15 @@ let sayHi = function(name) { // (*)
|
|||
};
|
||||
```
|
||||
|
||||
Function Expressions are created in the process of evaluation of the expression with them.
|
||||
Function Expressions are created in the process of evaluation of the expression with them. So, in the code above, the function is created and assigned to `sayHi` only when the execution reaches the line `(*)`.
|
||||
|
||||
So, in the code above, the function is created and assigned to sayHi only when the execution reaches line `(*)`.
|
||||
|
||||
Usually this is viewed as a bonus of the Function Declaration. Convenient, isn't it? Gives more freedom in how to organize our code.
|
||||
Usually, a Function Declaration is preferable because of that. It gives more freedom in how to organize our code.
|
||||
|
||||
## Anonymous functions
|
||||
|
||||
As a function is a value, it can be created on-demand and passed to another place of the code.
|
||||
|
||||
For instance, let's consider the following task, coming from a real-life.
|
||||
For instance, let's consider the following real-life task.
|
||||
|
||||
Function `ask(question, yes, no)` should accept a question and two other functions: `yes` and `no`. It asks a question and, if the user responds positively, executes `yes()`, otherwise `no()`.
|
||||
|
||||
|
@ -171,7 +193,7 @@ function ask(question, yes, no) {
|
|||
}
|
||||
```
|
||||
|
||||
In real-life `ask` is usually much more complex. It draws a nice windows instead of the simple `confirm` to ask a question. But that would make it much longer, so here we skip this part.
|
||||
In real-life `ask` will be usually much more complex, because it draws a nice windows and takes care about how to preent the `question` to the user, but here we don't care about that. Just `confirm` is enough.
|
||||
|
||||
So, how do we use it?
|
||||
|
||||
|
@ -200,79 +222,31 @@ ask("Should we proceed?",
|
|||
);
|
||||
```
|
||||
|
||||
So, we can declare a function in-place, right when we need it.
|
||||
So, we can declare a function in-place, exactly when we need it.
|
||||
|
||||
Such functions are sometimes called "anonymous" meaning that they are defined without a name.
|
||||
These functions are sometimes called "anonymous" meaning that they are defined without a name. So to say, we can't reuse this function anywhere outside of `ask`. And that's fine here.
|
||||
|
||||
And here, if we don't plan to call the function again, why should we give it a name? Let's just declare it where needed and pass on.
|
||||
Creating functions in-place is very natural and in the spirit of JavaScript.
|
||||
|
||||
That's very natural and in the spirit of JavaScript.
|
||||
|
||||
## new Function
|
||||
|
||||
Существует ещё один способ создания функции, который используется очень редко, но упомянем и его для полноты картины.
|
||||
|
||||
Он позволяет создавать функцию полностью "на лету" из строки, вот так:
|
||||
|
||||
```js
|
||||
//+ run
|
||||
let sum = new Function('a,b', ' return a+b; ');
|
||||
|
||||
let result = sum(1, 2);
|
||||
alert( result ); // 3
|
||||
```
|
||||
|
||||
То есть, функция создаётся вызовом `new Function(params, code)`:
|
||||
<dl>
|
||||
<dt>`params`</dt>
|
||||
<dd>Параметры функции через запятую в виде строки.</dd>
|
||||
<dt>`code`</dt>
|
||||
<dd>Код функции в виде строки.</dd>
|
||||
</dl>
|
||||
|
||||
Таким образом можно конструировать функцию, код которой неизвестен на момент написания программы, но строка с ним генерируется или подгружается динамически во время её выполнения.
|
||||
|
||||
Пример использования -- динамическая компиляция шаблонов на JavaScript, мы встретимся с ней позже, при работе с интерфейсами.
|
||||
|
||||
## Итого
|
||||
|
||||
Функции в JavaScript являются значениями. Их можно присваивать, передавать, создавать в любом месте кода.
|
||||
## Summary
|
||||
|
||||
<ul>
|
||||
<li>Если функция объявлена в *основном потоке кода*, то это Function Declaration.</li>
|
||||
<li>Если функция создана как *часть выражения*, то это Function Expression.</li>
|
||||
<li>
|
||||
Functions are values. They can be assigned, copied or declared in any place of the code.
|
||||
<ul>
|
||||
<li>If the function is declared as a separate statement -- it's called a Function Declaration.</li>
|
||||
<li>If the function is created as a part of an expression -- it's a Function Expression.</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>Function Declarations are processed before the code is executed. JavaScript scans the code, looks for them and creates corresponding functions.</li>
|
||||
<li>Function Expressions are created when the execution flow reaches them.</li>
|
||||
</ul>
|
||||
|
||||
Между этими двумя основными способами создания функций есть следующие различия:
|
||||
Novice programmers sometimes overuse Function Expressions. Somewhy, maybe not quite understanding what's going on, they create functions like `let func = function()`.
|
||||
|
||||
<table class="table-bordered">
|
||||
<tr>
|
||||
<th></th>
|
||||
<th>Function Declaration</th>
|
||||
<th>Function Expression</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Время создания</td>
|
||||
<td>До выполнения первой строчки кода.</td>
|
||||
<td>Когда управление достигает строки с функцией.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Можно вызвать до объявления </td>
|
||||
<td>`Да` (т.к. создаётся заранее)</td>
|
||||
<td>`Нет`</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Условное объявление в `if`</td>
|
||||
<td>`Не работает`</td>
|
||||
<td>`Работает`</td>
|
||||
</tr>
|
||||
</table>
|
||||
But in most cases Function Declaration is preferable.
|
||||
|
||||
Иногда в коде начинающих разработчиков можно увидеть много Function Expression. Почему-то, видимо, не очень понимая происходящее, функции решают создавать как `let func = function()`, но в большинстве случаев обычное объявление функции -- лучше.
|
||||
|
||||
**Если нет явной причины использовать Function Expression -- предпочитайте Function Declaration.**
|
||||
|
||||
Сравните по читаемости:
|
||||
Compare, which one is more readable:
|
||||
|
||||
```js
|
||||
//+ no-beautify
|
||||
|
@ -283,6 +257,7 @@ let f = function() { ... }
|
|||
function f() { ... }
|
||||
```
|
||||
|
||||
Function Declaration короче и лучше читается. Дополнительный бонус -- такие функции можно вызывать до того, как они объявлены.
|
||||
Function Declaration is shorter and more obvious. The additional bonus -- it can be called before the declaration.
|
||||
|
||||
Use Function Expression only when the function must be created at-place, inside another expression.
|
||||
|
||||
Используйте Function Expression только там, где это действительно нужно и удобно.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue