How to set up smartphones and PCs. Informational portal

JavaScript: Functions. Functional programming

JavaScript functions allow you to organize your scripts and make code easier to reuse. Instead of creating long snippets of code scattered throughout an HTML page, scripts are organized into logical groups.

Declaring and calling a JavaScript function

The JavaScript function syntax is as follows:

function ""name"" (""argument1"", ""argument2"", ""argument3"" ...) ( ""statements"" return ""value"" )

The name determines how we will call the function when it is called. The arguments specify the values ​​that are passed to the function for processing. The statements section is the body of the function that performs the processing. The optional return statement allows you to return a value.

The following example shows a function defined in an HTML page section and called in a section:

function sayHello() ( alert("Hello!"); ) sayHello();

Passing Arguments to a Function

In the example above (script type text JavaScript function ), no arguments are passed to the function. Usually, a function is designed to perform some action with several arguments:

A simple JavaScript function example function sayHello(day, month) ( alert("Hi! Today is " + day + " " + month); ) sayHello("24", "July"); sayHello("1", "August"); sayHello("24", "May");

In this example, the JavaScript callback function is called multiple times, taking arguments, which are then used to create the string that is displayed in the dialog box. To do this without a function, one would have to repeat the script in the section three times. Obviously using a function is the more efficient approach.

Returning a value from a function

The return statement is used to return a value from a function and use it at the point where the function is called. As an example, we will declare a function that adds two arguments and returns the result:

A simple JavaScript function example var result = addValues(10, 20) document.write("Result = " + result);

In the example above, we are passing the values ​​10 and 20 to the addValues ​​function. The addValues ​​function adds these two values ​​and returns the result. The return statement assigns the result to the result variable, which is then used to create a string to be displayed on the HTML page.

The JavaScript function call can be made in different places. For example, it is not necessary to assign the result as the value of a variable. You can use it directly as an argument when calling document.write .

It is important to note that a function can only return one value:

A simple example of a JavaScript function function addValues(value1, value2) ( return value1 + value2; ) document.write ("Result = " + addValues(10, 20)); JavaScript onclick functions can also be used in conditionals. For example: A simple JavaScript function example function addValues(value1, value2) ( return value1 + value2; ) if (addValues(10, 20) > 20) ( document.write ("Result > 20"); ) else ( document.write ( "Result< 20"); }

Where to place function declarations

There are two places where JavaScript function return declarations are recommended: inside a section of an HTML document, or in an external .js file. The second option is considered the most preferred location, as it provides the most flexibility.

The purpose of creating functions is to make them as generic as possible in order to maximize reusability.

The translation of the article Understanding JavaScript Functions was prepared by the friendly team of the project.

Good bad

Any programmer knows well what functions are and why they are needed. However, functions in the Javascript language have some peculiarities. If you have been programming in this language for a long time, then you probably know that there are different . If you came from another language, then when reading some articles, you most likely saw this, strange at first glance, function declaration:

Var add = function(arg1, arg2) ( var sum = arg1 + arg2; return sum; ) var result = add(5, 2); //result is now 7

That is, the function, firstly, does not have a name. Secondly, it is assigned to a variable, but not just assigned, but its body immediately goes. Personally, for me, who had previously written in such languages ​​as VB, C ++, such an announcement caused bewilderment and misunderstanding of how it works and why write like that at all.

I'm used to the "classic" function declaration and call, like this:

Function add(arg1, arg2) ( var sum = arg1 + arg2; return sum; ) var result = add(5, 3); //result is now 8

And this is where we come to the features of functions in Javascript. For ease of understanding, imagine that a function in JS is an ordinary value, such as a number or a string. You can write the number 5 into the result variable, right? Or something more complex, like an array, and then display it on the screen? You can. So, if we imagine that a function is an ordinary value, albeit a very complex structure, then the first way of declaring no longer seems to be something incredible.

The next interesting fact is a logical continuation of the first one. After we place data in a variable, we can pass data to another variable using the name of this variable:

Var a = 5; var b = a; alert(b); //outputs 5

The usual thing. Now take a look at this code:

Var add = function(arg1, arg2) ( var sum = arg1 + arg2; return sum; ) var calcSum = add; alert(calcSum(5, 6)); //outputs 11

Are you starting to guess? Since a function is like a variable, we can "propagate" it by ordinary assignment to other variables, turning them into functions as well. Now calcSum can also add two numbers. However, the code

VarcalcSum = add(1, 1); //calcSum is now equal to 2, this is not a function, but a variable with a number alert(calcSum(5, 6)); //error

It will not be executed, because in the first line we assigned not the function itself, but the result of its execution (parentheses indicate that the function should be executed, not assigned).

If you need to call a function on itself, then this is done as follows:

Var calcFact = function fact(val) ( if (val == 1) ? val: val * fact(val - 1); // calculate factorial using recursion ) alert(calcFact(4)); //outputs 24

Here, by assigning the function to a variable, we gave it the name fact. However, this name will only be available within the function itself and nowhere else. The reasons for this lie in the principle of the interpreter and are beyond the scope of the lesson.

You might be wondering, "Hmm, interesting feature! But what's the advantage of doing this? Are there situations where it's unavoidable or at least more convenient than a regular declaration?". I will not undertake to assert that there are situations where it is impossible to do without such an approach, but I can give an example where it reduces the amount of code. Let's say you need to greet a person depending on the time of day:

Var date = new Date(); var hello = (date.getHours()< 12) ? function() {alert("Доброе утро!")} : (date.getHours() < 18) ? function() {alert("Добрый день!")} : function() {alert("Добрый вечер!")}; hello();

As you can see, the functions are extremely simple, with a single alert command.

If we decided to go the "classic" way, then we would have to write three separate functions, and then call them in the time test condition:

Function goodMorning() ( alert("Good morning!"); ) function goodAfternoon() ( alert("Good afternoon!"); ) function goodEvning() ( alert("Good evening!"); ) var date = new Date (); (date.getHours()< 12) ? goodMorning() : (date.getHours() < 18) ? goodAfternoon() : goodEvning();

The code has grown significantly visually, even though we used the short form of the conditional statement. If we assume that the file contains really important functions that perform calculations, then polluting the list with such mini-functions that do not carry important logic, and which are most likely used only once, is not a good idea. In addition, we are forced to give each function a unique name and specify it when calling. Therefore, if you need to change the name of one of them, you will have to change it in two places, which increases the likelihood of an error.

Secondly, if we use the "classic" method, then we lose the ability to assign a function to a variable. That is, write

Function add(a, b) ( return a + b; ) var calcSum = add; calcSum(5, 5);

Already impossible. Therefore, in our example, if we still need to greet the guest more than once, we will have to duplicate this fragment each time:

(date.getHours()< 12) ? goodMorning() : (date.getHours() < 18) ? goodAfternoon() : goodEvning();

And in the first case, it will be enough to write just hello(); and the result will be the same.

I told you about an interesting feature of JS functions and gave examples. Thus, you have seen that the ways to call functions in Javascript are not limited to one single kind. Even if you cannot immediately find the use of these features in your projects, at least you will know that such features exist. And when a really good opportunity comes up, you can cut down on the amount of code and avoid unnecessary confusion and errors.!

The ideas of dynamically forming content on a web resource have become the norm. Static pages and template site building have 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).

A web resource at the moment a visitor arrives can be a couple of headers for the protocol, some text in the "head", a few lines of code in the "body" and that's it. The rest thinks of it» in the process of the visitor's work is an ideal site or aspiring to be one.

Place of description and essence of functions

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

The concept of an algorithm outside of a function is absent here in principle. Of course, a developer can insert a script anywhere on the page, put code in it, and it will be executed. But what is the point in code that is executed only once: when loading (reloading) the 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 the set of functions that is essential and significant, perhaps their mutual direct connection, but more often everything is different. The place of a function declaration and the place of its application are not at all the same thing.

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

Functional dynamics

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

The action on the page unfolds depending on its elements and the behavior of the visitor on it. Mouse movements, keyboard buttons, clicks, element events and other circumstances lead to the launch of the desired functions.

Initially, there is no sequence and there is no parallelism. Here there is an adequate reaction of the web resource to events. How fast JavaScript will execute a particular function depends on many technical (computer, 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 be executed after something, but there is not much point in this. It is important that JavaScript functions are the ability to create an adequate response to the visitor's actions.

This is new thinking in development: distributed processing of information in the depths 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. It doesn't make much sense to write another function inside a function, but it may be necessary for various and well-founded reasons.

The description of a function generally begins with the keyword "function", followed by its name, the list of arguments in parentheses separated by commas, and the body of the function in curly braces.

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

Function name and "function" parameter

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

It's also important to note here that WaitReplySC is a function. But in line scXHR.onreadystatechange = WaitReplySC it is passed as a parameter. This is a general rule of passing functions to other functions as parameters. Specified brackets and passed its parameter (parameters) into them - the function will be executed immediately. I gave only the name, so what. The function call will be made by the one who received its name.

The functionality implemented through AJAX allows you to call a JavaScript function through data received from the server. In fact, when sending a request to the server, a particular function may not at all “know” which function it is referring to and with what information.

Function exit and its result

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

If you want a function to return a result, you can use the JavaScript return operator: return. There can be a sufficient number of return statements in the body of a function. It is not necessary that they all return the same type of result.

Usually, developers greatly honor this opportunity and, depending on the situation, decide to leave the function as soon as possible.

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

Function Arguments

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

Inside the function, the arguments variable is available, which has a length property. You can access any function argument through arguments , arguments , ... until the last arguments .

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

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

arguments has a callee property that is intended to call a function that is currently executing. If you call itself, then the JavaScript version of the function in the function will allow you to implement recursion.

Using functions

Functions' primary concern is serving 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 specified per event.

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

A classic use of JS functions is event handlers on elements. In this example, the scfWecomeGo() or scfWelcomeCancel() function will be called in the login/logout form of the visitor, and when selecting the operation mode, scfMenuItemClick(this).

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

The function does not have to return a character string, a number, or another function. It can return a full-fledged HTML element, and in which there will be the required 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 rather difficult in terms of implementation.

Starting such a full-featured development, it is easy to get confused in your own code, in function calls, at the moments when this or that content of one or another part of the page is formed. Before taking such a 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 actually happens. It's hard, but the work is worth it.

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

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

Each case has its own functions. In other words, in such a simple example, it is necessary 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 are not related to events at all.

For example, when deleting a row, the lower ones should move up. To do this, you will either need to make a new selection, which is trite and capacious in terms of resources, or recalculate the lines, use array functions in javascript and elegantly achieve the goal.

Arguments and results of functions

JavaScript allows you to bring the code to a "full-functional" state. It is normal when the argument of a function is a function. It is possible for a function to return a function. JavaScript is completely relaxed about this.

This is a good mechanism, but rather complicated in terms of implementation. Technically, everything is permissible; only a qualified developer can semantically provide the logic for transferring “functionality”.

When in JavaScript a function is in a function - all right, but when a function generates a function, and that another one, then it is quite difficult to follow the logic. In fact, the question is not to apply qualifications, the question is to get a safe and correct result.

The concern of the developer is clear and simple. There is a task, 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 is passing a 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 will change and the result of the function execution will be. Depending on what is transferred, adequate changes will be made.

Execution of generated code

It is possible to implement the execution of code generated during the operation of another code by means of "eval". This is not considered a great solution, but often you can not complicate the code with unnecessary functions, but limit yourself to the banal formation of a line of JavaScript code and simply execute it.

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

The nuance of the JavaScript "function within a function" paradigm

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

A classic example of recursion: factorial calculation. Here it is quite difficult to write an algorithm that loops, but it is very easy to go beyond the bounds of the value. The factorial grows too fast.

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

For example, a regular table. There can be other tables in the table. Nesting cannot be limited. Writing a different 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 one cannot do without frills, the created system of functions, or rather its debugging and subsequent reliable operation, becomes the concern of not JavaScript, but the developer.

May 24, 2011 at 01:13 am Five ways to call a function
  • JavaScript
  • Translation

I often come across JavaScript code where errors are caused by a misunderstanding of how functions in JavaScript work (by the way, much of this code was written by me). JavaScript is a multi-paradigm language, and it has mechanisms for functional programming. It's time to explore these possibilities. In this article, I'll walk you through five ways to call functions in JavaScript.

In the early stages of learning JavaScript, beginners usually think that the functions in it work in much the same way as, say, in C#. But the mechanisms for calling functions in JavaScript have a number of important differences, and ignorance of them can result in errors that will not be easy to find.

Let's write a simple function that returns an array of three elements - the current this value and the two arguments passed to the function.
function makeArray(arg1, arg2)( return [ this, arg1, arg2 ]; )

The most common way: global call Beginners often declare functions as shown in the example above. Calling this function is easy:
makeArray("one", "two"); // => [ window, "one", "two" ]
Wait. Where did the window object come from? Why do we have this equal to window ?

In JavaScript, it doesn't matter if the script is running in a browser or some other environment, it is always defined global object. Any code in our script that is not "attached" to anything (that is, outside of an object declaration) is actually in the context of a global object. In our case, makeArray is not just a function running around on its own. In fact, makeArray is a method of the global object (in the case of code execution in the browser) window . It's easy to prove it:
alert(typeof window.methodThatDoesntExist); // => undefined alert(typeof window.makeArray); // => function
That is, calling makeArray("one", "two"); is equivalent to calling window.makeArray("one", "two"); .

It saddens me that this is the most common way to call functions, because it implies a global function. And we all know that global functions and variables are not the best form of programming. This is especially true for JavaScript. Avoid global definitions and you won't regret it.

Function calling rule #1: If a function is called directly without specifying an object (eg myFunction() ), the value of this will be the global object (window if the code is running in a browser).

Calling a method Let's create a simple object and make makeArray a method of it. We will declare the object using literal notation, and then we will call our method:
// create an object var arrayMaker = ( someProperty: "some value", make: makeArray ); // call the make() method arrayMaker.make("one", "two"); // => [ arrayMaker, "one", "two" ] // alternate syntax, use square brackets arrayMaker["make"]("one", "two"); // => [ arrayMaker, "one", "two" ]
See the difference? The value of this in this case is the object itself. Why not window , as in the previous case, because the function declaration has not changed? The whole secret is how functions are passed in JavaScript. Function is a standard JavaScript type that is actually an object, and just like any other object, functions can be passed and copied. In this case, we kind of copied the entire function, including the argument list and the body, and assigned the resulting object to the make property of the arrayMaker object. This is equivalent to this declaration:
var arrayMaker = ( someProperty: "Some value"; make: function (arg1, arg2) ( return [ this, arg1, arg2]; ) );
Function calling rule #2: In a function called using method invocation syntax such as obj.myFunction() or obj["myFunction"]() , this will be obj .

Failure to understand this simple, in general, principle often leads to errors in event handling:
function buttonClicked()( var text = (this === window) ? "window" : this.id; alert(text); ) var button1 = document.getElementById("btn1"); var button2 = document.getElementById("btn2"); button1.onclick = buttonClicked; button2.onclick = function()( buttonClicked(); );
Clicking on the first button will show the message btn1, because in this case we call the function as a method, and this inside the function will get the value of the object to which this method belongs. Clicking on the second button will display window, because in this case we are calling buttonClicked directly (i.e. not like obj.buttonClicked()). The same thing happens when we assign an event handler on the element tag, as in the case of the third button. Clicking on the third button will show the same message as for the second.

When using libraries like jQuery, you don't have to think about it. jQuery takes care of rewriting the this value in the event handler so that the this value is the element that fired the event:
// use jQuery $("#btn1").click(function() ( alert(this.id); // jQuery will make sure "this" is a button ));
How does jQuery manage to change the value of this ? Read below.

Two more ways: apply() and call() Logically, the more you use functions, the more often you have to pass them around and call them in different contexts. Often there is a need to override the value of this . If you remember, functions in JavaScript are objects. In practice, this means that functions have predefined methods. apply() and call() are two of them. They allow you to override the this value:
var car = ( year: 2008, model: "Dodge Bailout" ); makeArray.apply(car, [ "one", "two" ]); // => [ car, "one", "two" ] makeArray.call(car, "one", "two"); // => [ car, "one", "two" ]
These two methods are very similar. The first parameter overrides this . The differences between the two are in the subsequent arguments: Function.apply() takes an array of values ​​to be passed to the function, while Function.call() takes arguments separately. In practice, in my opinion, it is more convenient to use apply() .

Function calling rule #3: If you want to override the value of this without copying the function to another object, you can use myFunction.apply(obj) or myFunction.call(obj) .

Constructors I won't go into detail on declaring native types in JavaScript, but I feel it necessary to remind you that there are no classes in JavaScript, and any custom type needs a constructor. Also, custom type methods are best declared via prototype , which is a property of the constructor function. Let's create our own type:
// declare constructor function ArrayMaker(arg1, arg2) ( this.someProperty = "doesn't matter"; this. theArray = [ this, arg1, arg2 ]; ) // declare methods ArrayMaker.prototype = ( someMethod: function () ( alert( "Called someMethod"); ), getArray: function () ( return this.theArray; ) ); var am = new ArrayMaker("one", "two"); var other = new ArrayMaker("first", "second"); am.getArray(); // => [ am, "one", "two" ]
Important in this example is the presence of the new operator before the function call. If not for it, it would be a global call, and the properties created in the constructor would refer to the global object. We don't need this. Also, constructors usually don't explicitly return values. Without the new operator, the constructor would return undefined , with it it returns this . It is good style to name constructors with a capital letter; this will remind you of the need for the new operator.

Otherwise, the code inside the constructor will most likely be similar to the code you would write in another language. The value of this in this case is the new object you are creating.

Function calling rule #4: When a function is called with the new operator, the value of this will be a new object created by the JavaScript runtime. If this function does not explicitly return any object, this will be implicitly returned.

Conclusion Hopefully, understanding the difference between different ways of calling functions will enable you to improve your JavaScript code. Sometimes it is not easy to catch errors related to the value of this , so it makes sense to prevent them from occurring in advance.
  • Translation

I often come across JavaScript code where errors are caused by a misunderstanding of how functions in JavaScript work (by the way, much of this code was written by me). JavaScript is a multi-paradigm language, and it has mechanisms for functional programming. It's time to explore these possibilities. In this article, I'll walk you through five ways to call functions in JavaScript.

In the early stages of learning JavaScript, beginners usually think that the functions in it work in much the same way as, say, in C#. But the mechanisms for calling functions in JavaScript have a number of important differences, and ignorance of them can result in errors that will not be easy to find.

Let's write a simple function that returns an array of three elements - the current this value and the two arguments passed to the function.
function makeArray(arg1, arg2)( return [ this, arg1, arg2 ]; )

The most common way: global call Beginners often declare functions as shown in the example above. Calling this function is easy:
makeArray("one", "two"); // => [ window, "one", "two" ]
Wait. Where did the window object come from? Why do we have this equal to window ?

In JavaScript, it doesn't matter if the script is running in a browser or some other environment, it is always defined global object. Any code in our script that is not "attached" to anything (that is, outside of an object declaration) is actually in the context of a global object. In our case, makeArray is not just a function running around on its own. In fact, makeArray is a method of the global object (in the case of code execution in the browser) window . It's easy to prove it:
alert(typeof window.methodThatDoesntExist); // => undefined alert(typeof window.makeArray); // => function
That is, calling makeArray("one", "two"); is equivalent to calling window.makeArray("one", "two"); .

It saddens me that this is the most common way to call functions, because it implies a global function. And we all know that global functions and variables are not the best form of programming. This is especially true for JavaScript. Avoid global definitions and you won't regret it.

Function calling rule #1: If a function is called directly without specifying an object (eg myFunction() ), the value of this will be the global object (window if the code is running in a browser).

Calling a method Let's create a simple object and make makeArray a method of it. We will declare the object using literal notation, and then we will call our method:
// create an object var arrayMaker = ( someProperty: "some value", make: makeArray ); // call the make() method arrayMaker.make("one", "two"); // => [ arrayMaker, "one", "two" ] // alternate syntax, use square brackets arrayMaker["make"]("one", "two"); // => [ arrayMaker, "one", "two" ]
See the difference? The value of this in this case is the object itself. Why not window , as in the previous case, because the function declaration has not changed? The whole secret is how functions are passed in JavaScript. Function is a standard JavaScript type that is actually an object, and just like any other object, functions can be passed and copied. In this case, we kind of copied the entire function, including the argument list and the body, and assigned the resulting object to the make property of the arrayMaker object. This is equivalent to this declaration:
var arrayMaker = ( someProperty: "Some value"; make: function (arg1, arg2) ( return [ this, arg1, arg2]; ) );
Function calling rule #2: In a function called using method invocation syntax such as obj.myFunction() or obj["myFunction"]() , this will be obj .

Failure to understand this simple, in general, principle often leads to errors in event handling:
function buttonClicked()( var text = (this === window) ? "window" : this.id; alert(text); ) var button1 = document.getElementById("btn1"); var button2 = document.getElementById("btn2"); button1.onclick = buttonClicked; button2.onclick = function()( buttonClicked(); );
Clicking on the first button will show the message btn1, because in this case we call the function as a method, and this inside the function will get the value of the object to which this method belongs. Clicking on the second button will display window, because in this case we are calling buttonClicked directly (i.e. not like obj.buttonClicked()). The same thing happens when we assign an event handler on the element tag, as in the case of the third button. Clicking on the third button will show the same message as for the second.

When using libraries like jQuery, you don't have to think about it. jQuery takes care of rewriting the this value in the event handler so that the this value is the element that fired the event:
// use jQuery $("#btn1").click(function() ( alert(this.id); // jQuery will make sure "this" is a button ));
How does jQuery manage to change the value of this ? Read below.

Two more ways: apply() and call() Logically, the more you use functions, the more often you have to pass them around and call them in different contexts. Often there is a need to override the value of this . If you remember, functions in JavaScript are objects. In practice, this means that functions have predefined methods. apply() and call() are two of them. They allow you to override the this value:
var car = ( year: 2008, model: "Dodge Bailout" ); makeArray.apply(car, [ "one", "two" ]); // => [ car, "one", "two" ] makeArray.call(car, "one", "two"); // => [ car, "one", "two" ]
These two methods are very similar. The first parameter overrides this . The differences between the two are in the subsequent arguments: Function.apply() takes an array of values ​​to be passed to the function, while Function.call() takes arguments separately. In practice, in my opinion, it is more convenient to use apply() .

Function calling rule #3: If you want to override the value of this without copying the function to another object, you can use myFunction.apply(obj) or myFunction.call(obj) .

Constructors I won't go into detail on declaring native types in JavaScript, but I feel it necessary to remind you that there are no classes in JavaScript, and any custom type needs a constructor. Also, custom type methods are best declared via prototype , which is a property of the constructor function. Let's create our own type:
// declare constructor function ArrayMaker(arg1, arg2) ( this.someProperty = "doesn't matter"; this. theArray = [ this, arg1, arg2 ]; ) // declare methods ArrayMaker.prototype = ( someMethod: function () ( alert( "Called someMethod"); ), getArray: function () ( return this.theArray; ) ); var am = new ArrayMaker("one", "two"); var other = new ArrayMaker("first", "second"); am.getArray(); // => [ am, "one", "two" ]
Important in this example is the presence of the new operator before the function call. If not for it, it would be a global call, and the properties created in the constructor would refer to the global object. We don't need this. Also, constructors usually don't explicitly return values. Without the new operator, the constructor would return undefined , with it it returns this . It is good style to name constructors with a capital letter; this will remind you of the need for the new operator.

Otherwise, the code inside the constructor will most likely be similar to the code you would write in another language. The value of this in this case is the new object you are creating.

Function calling rule #4: When a function is called with the new operator, the value of this will be a new object created by the JavaScript runtime. If this function does not explicitly return any object, this will be implicitly returned.

Conclusion Hopefully, understanding the difference between different ways of calling functions will enable you to improve your JavaScript code. Sometimes it is not easy to catch errors related to the value of this , so it makes sense to prevent them from occurring in advance.

Top Related Articles