Мегафон

Как вызывать функцию в javascript. JavaScript: функция в функции. Язык программирования JS

Функция - это программный код, который определяется один раз и затем может вызываться на выполнение любое количество раз.

В JavaScript функция является значением, поэтому её можно присваивать переменным, элементам массива, свойствам объектов, передавать в качестве аргумента функциям и возвращать в качестве значения из функций.

Объявление и вызов функции

Существует три способа объявления функции: Function Declaration, Function Expression и Named Function Expression.

Function Declaration (сокращённо FD) – это "классическое" объявление функции. В JavaScript функции объявляются с помощью литерала функции. Синтаксис объявления FD:

Литерал функции состоит из следующих четырёх частей:

  • Ключевое слово function .
  • Обязательный идентификатор, определяющий имя функции. В качестве имени функции обычно выбирают глагол, т. к. функция выполняет действие.
  • Пара круглых скобок вокруг списка из нуля или более идентификаторов, разделяемых запятыми. Данные идентификаторы называются параметрами функции.
  • Тело функции, состоящее из пары фигурных скобок, внутри которых располагаются инструкции. Тело функции может быть пустым, но фигурные скобки должны быть указаны всегда.
  • Простой пример:

    Function sayHi() { alert("Hello"); }

    Встречая ключевое слово function интерпретатор создаёт функцию и затем присваивает ссылку на неё переменной с именем sayHi (переменная с данным именем создаётся интерпретатором автоматически).

    Обратившись к переменной sayHi можно увидеть, что в качестве значения там находится функция (на самом деле ссылка на неё):

    Alert(sayHi); // function sayHi() { alert("Hello"); }

    Function Expression (сокращённо FE) – это объявление функции, которое является частью какого-либо выражения (например присваивания). Синтаксис объявления FE:

    Function (параметры) { инструкции }

    Простой пример:

    Var sayHi = function () { alert("Hello"); };

    Функцию FE иначе ещё называют "анонимной функцией ".

    Named Function Expression (сокращённо NFE) – это объявление функции, которое является частью какого-либо выражения (например присваивания). Синтаксис объявления NFE:

    Function идентификатор (параметры) { инструкции }

    Простой пример:

    Var sayHi = function foo() { alert("Hello"); };

    Объявления FE и NFE обрабатываются интерпретатором точно так же, как и объявление FD: интерпретатор создаёт функцию и сохраняет ссылку на неё в переменной sayHi.

    Программный код, расположенный в теле функции, выполняется не в момент объявления функции, а в момент её вызова. Для вызова функции используется оператор () (вызов функции):

    Function sayHi() { alert("Hello"); } var sayHi2 = function () { alert("Hello2"); }; var sayHi3 = function foo() { alert("Hello3"); }; sayHi(); // "Hello" sayHi2(); // "Hello2" sayHi3(); // "Hello3"

    Разница между представленными тремя объявлениями заключается в том, что функции, объявленные как FD, создаются интерпретатором до начала выполнения кода (на этапе анализа), поэтому их можно вызывать (в той области видимости где они объявлены) до объявления:

    // Вызов функции до её объявления в коде верхнего уровня foo(); function foo() { alert("Вызов функции foo() в глобальной области видимости."); // Вызов функции до её объявления в области видимости функции bar(); function bar() { alert("Вызов функции bar() в области видимости функции."); } }

    Функции, объявленные как FE или NFE, создаются в процессе выполнения кода, поэтому их можно вызывать только после того как они объявлены:

    // sayHi(); // Ошибка. Функция sayHi ещё не существует var sayHi = function () { alert("Hello!"); }; sayHi();

    Функции, объявленные внутри блока, находятся в блочной области видимости:

    // foo(); // Ошибка. Функция не объявлена. { foo(); // 1 function foo() { console.log(1); } } foo(); // Ошибка. Функция не объявлена.

    В отличие от FE, функция, объявленная как NFE, имеет возможность обращаться к себе по имени при рекурсивном вызове. Имя функции доступно только внутри самой функции:

    (function sayHi(str) { if (str) { return; } sayHi("hi"); // Имя доступно внутри функции })(); sayHi(); // Ошибка. Функция не объявлена

    Функция обратного вызова

    Функция обратного вызова – это функция, которая передаётся в качестве аргумента другой функции для последующего её вызова.

    Функции обратного вызова часто используются, в качестве обработчиков событий.

    Ниже приведён пример функции, принимающей в качестве своего аргумента ссылку на другую функцию для её последующего вызова:

    Function foo(callback) { return callback(); } foo (function() { alert("Hello!"); });

    Этот пример наглядно демонстрирует принцип действия обратного вызова.

    Как создать функцию в JavaScript ? Такой вопрос достаточно распространён среди начинающих программистов. И эта статья написана как раз для таких новичков. Для начала необходимо разобраться с вопросом: а что такое функция? Давайте с этого и начнём.

    Вы должны помнить из школы, что такое функция. Если нет, то напоминаю. У функции есть определённые параметры, которыми она манипулирует, и возвращает результат. Например, функция y = 2 * x +5. Здесь мы можем задать x = 3, а в ответ получим y = 11. Вот это пример функции из математики. Абсолютно аналогичные функции и в JavaScript , только тут функцией может быть не просто какое-то вычисление какого-то выражения, а всё, что угодно.

    Давайте для начала создадим функцию, которая 3 раза выводит сообщение "Привет ".


    function hello() {
    alert("Привет");
    alert("Привет");
    alert("Привет");
    }
    hello();

    Первая строчка сообщает, что дальше идёт сценарий на языке JavaScript . На следующей строке объявляется функция. Как видите, всё начинается с ключевого слова function . Внутри скобок указываются параметры, но в данном случае параметров нет, поэтому внутри скобок всё пусто. Дальше идут фигурные скобки, внутри которых находится код функции, который должен быть выполнен при её вызове. В качестве этого кода используется функция alert() , которая вызывает информационное окошко, в котором написан текст, заданный параметром. В качестве параметра мы функции alert() (это пример встроенной функции) передаём строку "Привет ". Функцию alert() мы вызываем три раза.

    Когда функция написана, то необходимо поставить закрывающую фигурную скобку. На следующей строке мы вызываем функцию hello() . Надеюсь, Вам стало понятно, что такое функция. Возможно, что некоторые из Вас спросят: "А какие преимущества? Ведь мы могли бы просто написать три раза alert() и результат был бы тот же". Вы правы, и так и нужно поступать, если Вам нужно использовать этот код всего один раз. А представьте, что Вам это нужно 3, 4 или большее число раз. Разумеется, неудобно писать постоянно этот повторяющийся код. Гораздо проще написать одно слово hello(). Согласны? Думаю, что да. В конце статьи я, исходя из этого, сделаю один очень важный вывод, поэтому дочитайте её до конца.

    Теперь поговорим о функциях с параметрами. Давайте создадим один из таких примеров (буду писать сразу функцию и её вызов, без тега ).

    Function sum (x, y) {
    var sum = x + y;
    document.write(sum);
    }
    sum(5, 4);

    Код достаточно прозрачный, однако, давайте прокомментирую. Опять ключевое слово function , потом название функции (в данном случае, пусть будет sum ). Внутри скобок указал два параметра, которые требуются (x и y ). Внутри функции я создаю ещё одну переменную sum (это совершенно нормально называть переменные и функции одинаково), которой присваиваю сумму x и y (которые были переданы). И затем вывожу в окно браузера полученный результат. После функции вызываю её, передав параметры 5 и 4 . Вы можете проверить, и увидите в окне браузера - 9 .

    И, напоследок, скажу о возвращаемых значениях. В примере выше мы результат сразу печатали, однако, для данной функции будет наиболее логично ничего не печатать, а возвратить результат. А что дальше с ним делать - это уже другой вопрос. Давайте перепишем функцию так:

    Function sum(x, y) {
    var sum = x + y;
    return sum;
    }
    var z = sum(4, 5) + sum(1,-3);
    document.write(z);

    Обратите внимание на ключевое слово return . Оно возвращает результат (в нашем случае - сумму двух чисел). Таким образом, sum(4,5) возвращает 9 . Это число мы складываем с результатом работы функции sum(1, -3) , то есть -2 . В итоге мы получим 7 . И только потом печатаем результат в браузере.

    Надеюсь, Вы оценили возможности функций, поэтому создавать и использовать функции в JavaScript надо обязательно. И сейчас я сделаю один важный вывод, принцип, которому надо всегда следовать: любой повторяющийся код - необходимо выделять в отдельную функцию . Если у Вас 20 раз выводится одинаковые 5 строк (к примеру), то необходимо эти 5 строк выделить в отдельную функцию. Тем самым Вы вместо 100 строк (20 раз * 5 строк), напишите только 20 строк, да ещё и более понятных (название функции - это гораздо проще, чем 5 строк кода). Хочется сказать, что если этому правилу не следовать, то размер программы может увеличиться в десятки, а, может, и в сотни раз.

    Советую Вам потренироваться и, например, создать функции всех основных математических операций (сложение, вычитание, умножение и деление).

    Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure-a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

    A method is a function that is a property of an object. Read more about objects and methods in Working with objects .

    Calling functions

    Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square , you could call it as follows:

    Square(5);

    The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.

    Functions must be in scope when they are called, but the function declaration can be hoisted (appear below the call in the code), as in this example:

    Console.log(square(5)); /* ... */ function square(n) { return n * n; }

    The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.

    Note: This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work. That means, function hoisting only works with function declaration and not with function expression.

    Console.log(square); // square is hoisted with an initial value undefined. console.log(square(5)); // TypeError: square is not a function var square = function(n) { return n * n; }

    The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props() function (defined in ) is an example of a function that takes an object as an argument.

    A function can call itself. For example, here is a function that computes factorials recursively:

    Function factorial(n) { if ((n === 0) || (n === 1)) return 1; else return (n * factorial(n - 1)); }

    You could then compute the factorials of one through five as follows:

    Var a, b, c, d, e; a = factorial(1); // a gets the value 1 b = factorial(2); // b gets the value 2 c = factorial(3); // c gets the value 6 d = factorial(4); // d gets the value 24 e = factorial(5); // e gets the value 120

    There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the Function object). One of these, the apply() method, can be used to achieve this goal.

    Function scope

    Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.

    // The following variables are defined in the global scope var num1 = 20, num2 = 3, name = "Chamahk"; // This function is defined in the global scope function multiply() { return num1 * num2; } multiply(); // Returns 60 // A nested function example function getScore() { var num1 = 2, num2 = 3; function add() { return name + " scored " + (num1 + num2); } return add(); } getScore(); // Returns "Chamahk scored 5"

    Scope and the function stack Recursion

    A function can refer to and call itself. There are three ways for a function to refer to itself:

  • the function"s name
  • an in-scope variable that refers to the function
  • For example, consider the following function definition:

    Var foo = function bar() { // statements go here };

    Within the function body, the following are all equivalent:

  • bar()
  • arguments.callee()
  • foo()
  • A function that calls itself is called a recursive function . In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:

    Var x = 0; while (x < 10) { // "x < 10" is the loop condition // do stuff x++; }

    can be converted into a recursive function and a call to that function:

    Function loop(x) { if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)") return; // do stuff loop(x + 1); // the recursive call } loop(0);

    However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:

    Function walkTree(node) { if (node == null) // return; // do something with node for (var i = 0; i < node.childNodes.length; i++) { walkTree(node.childNodes[i]); } }

    Compared to the function loop , each recursive call itself makes many recursive calls here.

    It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.

    The stack-like behavior can be seen in the following example:

    Function foo(i) { if (i < 0) return; console.log("begin: " + i); foo(i - 1); console.log("end: " + i); } foo(3); // Output: // begin: 3 // begin: 2 // begin: 1 // begin: 0 // end: 0 // end: 1 // end: 2 // end: 3

    Nested functions and closures

    You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure . A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

    Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.

    • The inner function can be accessed only from statements in the outer function.
    • The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.

    The following example shows nested functions:

    Function addSquares(a, b) { function square(x) { return x * x; } return square(a) + square(b); } a = addSquares(2, 3); // returns 13 b = addSquares(3, 4); // returns 25 c = addSquares(4, 5); // returns 41

    Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:

    Function outside(x) { function inside(y) { return x + y; } return inside; } fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give // it result = fn_inside(5); // returns 8 result1 = outside(3)(5); // returns 8

    Preservation of variables

    Notice how x is preserved when inside is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside is no longer accessible.

    This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.

    Multiply-nested functions

    Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining . (Why it is called "chaining" will be explained later.)

    Consider the following example:

    Function A(x) { function B(y) { function C(z) { console.log(x + y + z); } C(3); } B(2); } A(1); // logs 6 (1 + 2 + 3)

    In this example, C accesses B "s y and A "s x . This can be done because:

  • B forms a closure including A , i.e. B can access A "s arguments and variables.
  • C forms a closure including B .
  • Because B "s closure includes A , C "s closure includes A , C can access both B and A "s arguments and variables. In other words, C chains the scopes of B and A in that order.
  • The reverse, however, is not true. A cannot access C , because A cannot access any argument or variable of B , which C is a variable of. Thus, C remains private to only B .

    Name conflicts

    When two arguments or variables in the scopes of a closure have the same name, there is a name conflict . More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:

    Function outside() { var x = 5; function inside(x) { return x * 2; } return inside; } outside()(10); // returns 20 instead of 10

    The name conflict happens at the statement return x and is between inside "s parameter x and outside "s variable x . The scope chain here is { inside , outside , global object}. Therefore inside "s x takes precedences over outside "s x , and 20 (inside "s x) is returned instead of 10 (outside "s x).

    Closures

    Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of encapsulation for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the duration of the outer function execution, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

    Var pet = function(name) { // The outer function defines a variable called "name" var getName = function() { return name; // The inner function has access to the "name" variable of the outer //function } return getName; // Return the inner function, thereby exposing it to outer scopes } myPet = pet("Vivie"); myPet(); // Returns "Vivie"

    It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

    Var createPet = function(name) { var sex; return { setName: function(newName) { name = newName; }, getName: function() { return name; }, getSex: function() { return sex; }, setSex: function(newSex) { if(typeof newSex === "string" && (newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")) { sex = newSex; } } } } var pet = createPet("Vivie"); pet.getName(); // Vivie pet.setName("Oliver"); pet.setSex("male"); pet.getSex(); // male pet.getName(); // Oliver

    In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner functions act as safe stores for the outer arguments and variables. They hold "persistent" and "encapsulated" data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

    Var getCode = (function() { var apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... return function() { return apiCode; }; })(); getCode(); // Returns the apiCode

    There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.

    Var createPet = function(name) { // The outer function defines a variable called "name". return { setName: function(name) { // The enclosed function also defines a variable called "name". name = name; // How do we access the "name" defined by the outer function? } } }

    Using the arguments object

    The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:

    Arguments[i]

    where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments . The total number of arguments is indicated by arguments.length .

    Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don"t know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

    For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

    Function myConcat(separator) { var result = ""; // initialize list var i; // iterate through arguments for (i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; }

    You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

    // returns "red, orange, blue, " myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; " myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // returns "sage. basil. oregano. pepper. parsley. " myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

    Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

    Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this .

    Shorter functions

    In some functional patterns, shorter functions are welcome. Compare:

    Var a = [ "Hydrogen", "Helium", "Lithium", "Beryllium" ]; var a2 = a.map(function(s) { return s.length; }); console.log(a2); // logs var a3 = a.map(s => s.length); console.log(a3); // logs

    No separate this

    Until arrow functions, every new function defined its own value (a new object in the case of a constructor, undefined in function calls, the base object if the function is called as an "object method", etc.). This proved to be less than ideal with an object-oriented style of programming.

    Function Person() { // The Person() constructor defines `this` as itself. this.age = 0; setInterval(function growUp() { // In nonstrict mode, the growUp() function defines `this` // as the global object, which is different from the `this` // defined by the Person() constructor. this.age++; }, 1000); } var p = new Person();

    In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be closed over.

    Function Person() { var self = this; // Some choose `that` instead of `self`. // Choose one and be consistent. self.age = 0; setInterval(function growUp() { // The callback refers to the `self` variable of which // the value is the expected object. self.age++; }, 1000); }

    В этой главе:

    Функции – это один из основных способов объединения операторов в логически связанные блоки. В языке JavaScript функция представляет собой группу выражений, служащих для выполнения какой-либо определенной задачи, объединенных под общим именем.

    В отличие от большинства других языков программирования, JavaScript не делает различий между собственно функциями и процедурами. Подобно функциям, процедуры так же представляют собой программные блоки. Однако результаты выполнения процедур непосредственно сказываются на выполнении программы, в то время как функции должны возвращать значения. С этой точки зрения функции JavaScript можно рассматривать и как процедуры.

    Определение и вызов функций

    Прежде, чем вызывать и использовать функцию, ее надо определить. Определение функций в JavaScript имеет следующий синтаксис:

    Function ИмяФункции (аргументы) { блок выражений }

    Таким образом, функция состоит из следующих частей, предваряемых ключевым словом function:

    • идентификатора, определяющего имя функции;
    • списка аргументов, заключенного в круглые скобки и разделенного запятыми;
    • операторов JavaScript, заключенных в фигурные скобки. Эти операторы могут включать вызовы других функций или даже самой этой функции (рекурсия).

    В простейшем случае аргументы могут отсутствовать, а блок операций моет быть представлен единственным оператором:

    Function MyFirstFunc () { var MyMessage="Это – моя функция!"; alert(MyMessage); }

    Здесь мы определили функцию, которая будет выдавать окно с сообщением «Это – моя функция!». Следует заметить, что даже если функция не принимает никаких аргументов, она все равно должна иметь пару круглых скобок после своего названия.

    ВНИМАНИЕ
    Важное замечание следует сделать по поводу переменных, объявляемых в теле функций. Такие переменные видны программе только внутри той функции, в которой они определены. Так, в примере с MyFirstFunc, доступ к переменной MyMessage возможен только внутри этой функции, но не вне нее.

    Но чаще всего функции все-таки принимают какие-либо значения в качестве своих аргументов. Возьмем для примера ранее рассмотренный блок, вычисляющий список чисел, на которые 100 делится без остатка. Если этот блок вынести в отдельную функцию, то можно будет использовать его для того, чтобы выводить список делителей для любого числа. Для этого нам потребуется всего один аргумент, который и будет определять число, для которого нам нужно получить такой список:

    Function remainder_free(j) { var i=0; while (i