Javascript This

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Understanding This JavaScript Keyword

If you want to become a programmer, no matter what specific field you choose, you will definitely have to deal with JavaScript. It has evolved from humble beginnings into a true powerhouse. Now it covers frontends, backends, mobile devices, games, desktop applications, and even machine learning !

Now, before you become a JavaScript master and develop, you need to learn the basics . The keyword this should probably be number one on your learning list.

What is doing?

Simply put, this is a pointer, a way to refer to what object called a function or method in JavaScript code. Just put, this is what is to the left of the dot

 JjwTQxuP6L WmnDmCG8KVxY0rcjZVSpOloMuMF8quXCZ2iG4sSq AzXI5sBi0Av4xuGKlQC9tsawIgadlXznOZZQb5LJ4vzz7yj FaUJbG2xN6u83AZzVQ6f3BGc3pvDq0GK3 41

This has two main uses. Let them explore with a few examples.

Building objects with this

The above code produces the following output:

 HdZ8KT6WIQorNxAykqXF37AjSU5n5GBPIeyft87 KFpUfmNGCwi0WEKYvtCB1d9usWt9gnoC8ww9nBMzQ6zPc8Qsc9 UdyDo6rPPxIzVUFG0lvSRFu3sgQv EtvT1m5VwzFZkdHb

here, we have defined a constructor where we are subject of books that take a title, author, and genre as parameters.

a constructor function is a "project" function object from which we can create objects with the given name (book in our case).

We have created an object called myBook and successfully passed the required parameters (called arguments when we call or invoke a function, as opposed to parameters when we define).

Finally, we saved myBook and retrieve the object with its corresponding properties. In this way, each new book object, we create gets transmitted values that are his assigned

Access to properties with this .

O125HABjebQCK3nPhbNzUnler0bcpANJ7OaCvMzhTuCzNJ2gPQ2EqmsRJLO1TlzfqEEb8jCLoxh0Sc VKhRez31dmx EzA8iCEtbwenZpKqGGgYzbL0FH4DHG0cAuM N7sQrJBrd

Here we have defined a child variable called which owns an object with name and property age, and a function to introduce.

The function records an introductory sentence using the properties of the object, accessed with ce .wanted_property.

This and JavaScript scope

By default, when used in global scope, that is, not in a defined function or object , this will refer to the global object. In the browser, the window is the global object.

When you declare primitive data (strings, numbers, booleans ...), an object or a function in JavaScript, they are all attached to the global object (window).

Anything you write "in the open‚", you can read it as if there was a window. written before. Let’s take a look at this code snippet:

First , we define a function called returnThis in global scope that returns the value of this. We therefore call by writing returnThis ().

Since it has global scope, we can see it as window.returnThis (), which return what’s left of the point.

WzxQs1F MhsmPGRiqznE7ozZ3mc7YadBtBxOpg HAb9Zct63750Htg MOpLfexOmr0MsF6J1kYh5qW08j8yOGxvA7lcGQV2szpq8dikff6gUHYM3qB5aRufrcNtgqSrFCZ3o8L R

object functions aka methods

If we now define a new object that has the same function in its interior (called method object) and call it once more, we are going to get this object (indicated by the braces) returned.

DY9zooKnmmI8Vc37PBbHjBp5zxhuyC71xVOq Figk93sVGvHleGzrvzfh9OmSpb0GetDPZ2atUf O8fRM T3eQ GCt5BqQC37UAj JrIA4LEecmtMLaPoA05Dyq6 Cn2hq2q12x

the Gotcha of this and its three solutions

If a function is not directly related to an object, the this in the function will refer to the global object.

Eseguiamo questo nel browser e vediamo cosa otteniamo:

 CtomF3s8FMLS1oewOnL IOJq Z4iLFzF EFxZb GPsC2Wdnq2VHyA1p UMuqIxl8S2lFKX725 OX 0ThuNdTfSxN90zVaalIVwkSQRAO92yrlYZHeS5zCyvEaBT CCOI6xfErF5

definito a oggetto che con una funzione restituisce questo di nuovo e un’altra che restituisce una funzione interna, che quindi restituisce questo.

Quando vogliamo chiamare la funzione indirettaNestedFunction, prima scriviamo () una volta per chiamare the funzione esterna che restituisce the interno.

Poi chiamiamo the interno con un altro () che restituisce la window.

This is one of the mysterious behaviors of JavaScript and gives rise to some unexpected and unwanted surprises.

Fortunately, there are ways to fix this problem. The first one is closing href = "/ javascript-closure/">, which is the way it was done before ES6. The second way is to use the arrow functions , and the third is to use the bind method, which is closely related to the call and apply of methods.

# 1 Resolution this with closures

a closure is a persistent memory bank, which means that the variable does not disappear when the finishes of runtime function . It is created by the JavaScript engine when a nested function references a variable defined in an external function so that it can be accessed even when the external execution functions finishes . Here’s what our this example looks like:

O4GbqSXJ POMJIcI CENugweH2RZznl9MpRUuz FfUplXjsm UWrgXqHMH 7mJCrFUFmInJoidY4VWOqH42bGUeHbqfCHVAc S06jt20eOixDxOrgD33vq <this variable, we have defined an object. Since the closing function is directly related to the <object that contains it, the value of <em>this</em> now refers to it , included in our function. em> this</em> usually refers to the window object Since we used an access closure <em>ce</em> of the container function, we are able to preserve the object calling its value . </p> <style div = ?

# 2 Solve this with arrow functions

The second solution probably uses one of the best features that come with ES6, which are the arrow functions .

Arrow functions represent a more concise syntax for write functions , and they search a higher level as part of the search for this, in the sense of the function in which it is contained

so, if we define our object like this .

K 3o0FbhIsz9kparusxhgcIyjT98cdj9x3cmIK4z6s3ufFSOpJU9GRi8MFolSpEUjWymOYkXjLTv575y5BpQP2G ZxurB 4X DxM0VxuTL71xvhLpnDOwOKyALsQ5EmuWhZTyVKI < / figure>

Our object has an outer function which, when called, returns the inner regular function.

We then call regularFunction and return the innermost function of the arrow.

, when called, it returns the window object .

An arrow function searches only level 1 scope. Since the containing regularFunction is not directly related to our object, the window is returned.
However,

If, we nest an arrow function inside an arrow function, in a regular function, will get the expected result, which is the actual container object.

GEmZMbwXOUTjun VLAnqHPB4lNvQtSmz Jh QOUZTXemGivcl0fh2Q7Zi W GAcYKVdZoJ5kOP78zQcyBIxv2X66rBmRD0ZyGoxDZbKCFA915KmiNfP4HZZt> the arrow function inside looks the outside is also an arrow function, so look for another level. The normal external function is directly related to the call

object and, therefore, the object is what is returned as this .

# 3 Solve this with the bind method

Finally, the third solution uses the bind method. the binding method is used to explicitly declare what this need Gets the object passed an argument and associates it with this keyword of the function.

OOwVv6pM0 9P TJE8s3RnElxcOrpJBU4iz8a9IePz CQA7pj4yW1tqVBYW6x6YSYlv5ukV7tweKh8gO7bNGjrl PVuMSLI5rFbxJ FjBT66zjXTpieemYxTMs781Bmz4go79j13t

In this example, we link chained to the function that normally returns the window object this . Pass it the object we want to refer to as this as an argument and our problem is solved.

This is not difficult when you understand JavaScript

Phew! It was a great dive. Now you may be wondering , why all the hassle and confusion with this

The reason is that, unlike everything else in JavaScript, this < / em> it is dynamic so coveted. This means that the JavaScript engine defines what what represents at runtime when the code is executed, observing where it came from and who is calling it.

At theinverse, everything else in JavaScript is lexically discovered, meaning that its value is set when the variable is set, when code is written.

Thanks to this, we can create a "project" object once and dynamically create objects with different property values ‚Äã‚Äãas we have seen in our example of book.

We can also create methods that expose and manipulate the properties of an object with this .wanted_property.

We can work around the quirks of JavaScript and control its behavior with confidence and the desired results.

Now that you understand this in JavaScript, along with a few other fundamental concepts, you can experiment, practice and take the safest action to or control JavaScript.

You that

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Javascript This, check other __main__ Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Jan Porretti

Milan | 2023-02-09

Maybe there are another answers? What Javascript This exactly means?. Will get back tomorrow with feedback

Dmitry Danburry

London | 2023-02-09

Simply put and clear. Thank you for sharing. Javascript This and other issues with numbers Python module was always my weak point 😁. Will get back tomorrow with feedback

Oliver Williams

New York | 2023-02-09

Expect PHP module is always a bit confusing 😭 Javascript This is not the only problem I encountered. I just hope that will not emerge anymore

Shop

Gifts for programmers

Learn programming in R: courses

$FREE
Gifts for programmers

Best Python online courses for 2022

$FREE
Gifts for programmers

Best laptop for Fortnite

$399+
Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best computer for crypto mining

$499+
Gifts for programmers

Best laptop for Sims 4

$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically