JavaScript: function in function. JS programming language

Ideas for dynamically generating content on a web resource have become the norm. Static pages and template site building finally completed their mission.

However, a modern web resource does not have to be represented by a set of pages generated by the server and updated by the browser (JS + AJAX).

javascript function in function

A web resource at the time a visitor arrives can be a couple of headers for the protocol, a little text in “head”, a few lines of code in “body” and that’s all. The rest is “ guessed ” during the work of the visitor - this is an ideal site or striving to be one.

Place of description and essence of functions

JavaScript is an experience gained over many decades. It has a significant development history, a modern qualified team of creators, developers. The language is well thought out, reliable, beautiful and provides a real opportunity for developers to write decent code and improve themselves.

javascript error the operation is insecure

The concept of an algorithm outside a function is absent here in principle. Of course, the developer can paste the script anywhere in the page, put the code into it and it will be executed. But what's the point in code that is executed only once: when loading (reloading) a page? Unless you can set the initial values ​​of some insignificant variables.

A script is a place to describe the necessary variables and functions, rather than a good piece of code written for its own sake. It is a set of functions that is essential and significant, perhaps their mutual direct connection, but more often it happens differently. The place of description of the function and the place of its application are not at all the same.

It is not necessary at all that a function will call another function directly; it can be done indirectly through dynamic code generation. The visitor makes a decision within the framework of this code and a completely different system of functions is triggered.

Functional dynamics

Functional dynamics are not only and not so much handlers assigned to page elements, these are functions that form page elements, and direct handlers can also change.

javascript return

The action on the page takes place depending on its elements and the behavior of the visitor on it. Mouse movements, keyboard buttons, clicks, item events, and other circumstances lead to the launch of the necessary functions.

Initially, there is no sequence and no parallelism. There is an adequate reaction of the web resource to events. How quickly JavaScript fulfills a particular function depends on many technical (computer logic, communication lines) and semantic (algorithm logic, subject area, task meaning) factors.

In fact, it can be argued that something worked in parallel, and something will come true after something, but there is no point in this. It is important that JavaScript functions are the ability to create an adequate response to visitor actions.

This is a new thinking in development: distributed information processing in the bowels of a single browser!

Syntax of Variables and Functions

JavaScript variables are placed both in the script tag and in the body of the function. Functions are defined in the same way. There is no particular sense in writing another function inside a function, but this may be necessary for various and quite justified reasons.

The description of the function in the general case begins with the keyword “function”, followed by its name, a list of arguments in parentheses, separated by a comma, and the body of the function in curly brackets.

javascript pass function to function

This example describes two functions that provide AJAX exchange between a page and a server. The scXHR variable is described above, therefore it is available both in InitXML and inside WaitReplySC.

Function Name and Function Parameter

An asynchronous option was introduced here when a JavaScript function in a function is called after a server response. At the same time, having received a response from the server, WaitReplySC accesses the page tags, fills them with the received information and calls other functions that may well initiate the next request to the server.

It is also important to note here that WaitReplySC is a function. But in the line scXHR.onreadystatechange = WaitReplySC it is passed as a parameter. This is a general rule for passing functions to other functions as parameters. He indicated the brackets and passed their parameter (s) to them - the function will be executed immediately. Passed only the name, so what. A function call will be made by the one who received her name.

The functionality implemented through AJAX allows you to make a JavaScript function call through the data received from the server. In fact, when sending a request to the server, this or that function may not even “know” what function it is accessing and with what information.

Exiting a function and its result

In the body of the function, you can write any language operators, which, in fact, is intended for this. Variables are available inside the function that are described inside and outside it, but not those described in other functions.

javascript function call

If you want the function to return a result, you can use the JavaScript return statement: return. There may be enough return statements in the body of the function. It is not necessary that all of them return a result of the same type.

Usually, developers greatly honor this opportunity and, depending on the situation, make a decision to exit the function as soon as it becomes possible.

It is not necessary to run through the entire algorithm of the function when you can exit earlier.

Function Arguments

Arguments to a function are transferred by a comma-separated list, are enclosed in parentheses, and are located immediately after its name. Variable names are used as arguments, but you can also pass values ​​directly. To pass a function to a function in JavaScript, you just need to specify its name without parentheses.

javascript variables

Inside the function, the arguments variable is available, which has the length property . You can access any function argument through arguments [0], arguments [1], ... up to the last arguments [arguments.length-1].

Changing the argument of a function is valid inside the function, but not outside of it. In order to change something outside the function, you need to use the JavaScript return operator, through which to pass the necessary value to the outside.

After the function completes the work, everything that was associated with its execution will be destroyed. At run time, a function can change external variables, except those described in other functions, including internal ones.

Arguments has a callee property that is designed to call a function that is currently executing. If you call yourself, then the JavaScript function in the function will allow you to implement recursion.

Using Functions

The main concern of functions is to serve browser events. To do this, almost every tag has the ability to specify the name of the event and the function that processes it. You can specify multiple events, but only one function is indicated for each event.

One function can serve several page elements and several events. Using the “this” parameter, you can pass information to the function where it was called from.

The classic use of JS functions is event handlers on elements. In this example, the scfWecomeGo () or scfWelcomeCancel () function will be called in the visitor's entry / exit form, and scfMenuItemClick (this) when choosing the operating mode.

javascript return

In the latter case, the parameter “this” is passed, which allows you to miraculously find out which particular divine the call came from. In general, JavaScript is so qualitatively implanted in the DOM and it is so convenient to navigate through its elements, to collect the necessary information, that page dynamics can be simply unpredictable.

A function does not have to return a character string, number, or other function. It can return a full HTML element, and in which there will be the necessary number of elements, with its own event handlers.

By placing such an element on the page, the developer creates new functionality, which is good in terms of solving the problem and satisfying the interests of visitors, but quite difficult in terms of implementation.

Starting such a fully functional development, it is easy to get confused in your own code, in function calls, at the moments when this or that content of this or that part of the page is formed. Before you take this direction of development, it does not hurt to weigh everything well.

About distributed thinking

The developer has to think at the level of all elements of the page, at the level of all events and have a clear idea of ​​how everything really happens. It is difficult, but this work is worth it.

javascript array functions

In JavaScript, the execution of a function can be delayed to some event, and there can be many such functions, and events have the property to spread and fall into the "scope" of various handlers.

javascript error the operation is insecure

In this example, somewhere earlier, a function was called that initiated the creation of a file navigation menu item. The page organization is supposed, that is, in the window there are only seven files that can be deleted and processed. You can navigate either by clicking on a file line, or by arrows on the keyboard, or in blocks of seven lines.

In each case, there are functions. In other words, in such a simple example, you need to write a couple of dozen functions that will respond to various events, and some of these functions will handle various options and situations that do not apply to events at all.

javascript function execution

For example, when deleting a row, the bottom should shift up. To do this, you will either need to make a new selection, which is trivial and resource-intensive, or to recount the lines, use array functions in javascript and elegantly achieve the goal.

Arguments and function results

JavaScript allows you to bring the code to a "fully functional" state. It is normal when the function argument is a function. The option is allowed when the function returns the function. JavaScript takes this quite calmly.

This is a good mechanism, but rather complicated in terms of implementation. Technically, everything is permissible, semantically, to ensure the logic of the transfer of “functional” only to a qualified developer.

javascript pass function to function

When in JavaScript a function is in a function - wherever it goes, but when a function generates a function, and that one is another, then it’s quite difficult to keep track of the logic. In fact, the question is not to apply qualifications, the question is to get a safe and correct result.

The developer’s concern is clear and simple. There is a problem, a solution is needed, and not an error like “JavaScript error the operation is insecure”, a blank screen or stopping the entire browser engine.

If the argument is a function, then the developer passes the variable with special properties, that is, it is not a number, not a string, not an object. But the use of such an argument can lead to the fact that external variables change and the result of the function execution is. Depending on what will be transferred adequate changes.

Execution of generated code

It is possible to implement the execution of code generated in the process of another code using “eval”. This is not considered an excellent solution, but often you can not complicate the code with unnecessary functions, but confine yourself to the banal formation of a string of JavaScript code and simply execute it.

function returns javascript function

In this example, a line is inserted to insert some information into the current div. The number of the diva and the content of the information are different for different positions, because such a solution in this situation is not guaranteed to provide the situation “javascript error the operation is insecure”, but it will reliably give the desired effect.

Author's example is not a picture

The nuance of the JavaScript function-in-function paradigm

If there is an opportunity to do without frills, it is better to use it. All of these options are good. Of course, in many cases this is the only solution.

A classic example of recursion: factorial calculation. It’s hard enough to write an algorithm that goes in cycles, but it’s very simple to go beyond the bounds of a value. Factorial is growing too fast.

However, both recursion and a function that calls another function that can make a valid callback are the norm.

For example, a regular table. There may be other tables in the table. Nesting cannot be limited. Writing your own set of functions for each table is too much of a luxury.

There are many such examples, and all these will be real and urgent tasks, not at all from the field of programming. That is why the problem lies precisely in the fact that you can’t do without frills, the created system of functions, more precisely its debugging and subsequent reliable work, becomes the concern not of JavaScript, but of the developer.

Source: https://habr.com/ru/post/K14846/


All Articles