Function is value

Lecture




  1. Function is value
  2. Copying functions

In this section, we will introduce important features of functions in JavaScript, as well as three ways to declare a function.

Function is value

In JavaScript, a function is a value, the same as a string or a number.

A declaration creates a function and writes a reference to it in a variable .

Like any value, the function can be output like this:

1 function sayHi() {
2    alert( 'Привет' );
3 }
4
5 alert(sayHi); // выведет код функции

Here it is not the result of the sayHi() function that is sayHi() way, what is it equal to? .. correct, undefined , because there is no return ), but the function itself, i.e. its code.

A function is not just a value, it is an object.

You can even write a property to it:

1 function sayHi() { }
2
3 sayHi.test = 5;
4
5 alert(sayHi.test); // 5

This feature is rarely used.

Copying functions

The function can be copied to another variable.

1 function sayHi(person) {
2    alert( 'Привет, ' + person);
3 }
4
5 var func = sayHi;
6
7 alert(func); // выведет код функции

At the same time, since a function is an object, it is copied “by reference”.

That is, the function itself lies somewhere in memory, and the variable contains the “address” where it is located. When assigning func = sayHi this address is copied, both variables begin to point to the same “place in memory” where the function is located.

After copying it can be called:

1 function sayHi(person) {
2    alert( 'Привет, ' + person);
3 }
4
5 var func = sayHi;
6
7 func( 'Вася' ); // выведет 'Привет, Вася'
8
9 sayHi( 'Маша' ); // и так по-прежнему работает: 'Привет, Маша'

Note again that the call of the form alert(func) is different from alert( func() ) . In the first case, the function (its code) is output, in the second, this function is called, and its result will be output.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone