📜 ⬆️ ⬇️

This keyword in javascript for beginners

The author of the material, whose translation we are publishing today, says that when she worked in the field of accounting, there were used clear terms, the meanings of which are easily found in the dictionary. But taking up programming, and, in particular, JavaScript, she began to deal with such concepts, which are no longer to be defined in dictionaries. For example, this concerns the keyword this . She recalls the time when she met JS objects and constructor functions that used this keyword, but it was not so easy to get to its exact meaning. She believes that similar problems arise in front of other newbies, especially those who have not worked on programming before. Those who want to learn JavaScript, in any case, will have to deal with this . This material aims to help everyone in this.



What is this?


I bring to your attention my own definition of the keyword this . This is a keyword used in JavaScript that has a special meaning depending on the context in which it is applied.

The reason why this causes so much confusion among newbies is that this context changes depending on its use.
')
This can be considered a dynamic keyword. I love how the concept of “context” is covered in this article by Ryan Morra. According to him, the context is always the value of the this , which refers to an object “owning” the code currently being executed. However, the context that relates to this is not the same as the execution context.

So, when we use this , we actually refer to an object with its help. Let's talk about what kind of object, having considered a few examples.

Situations when this points to a window object


If you try to access the this in the global scope, it will be tied to the global context, that is, to the window object in the browser.

When using functions that are in the global context (this distinguishes them from the methods of objects), the this in them will point to the window object.

Try to execute this code, for example, in the browser console:

 console.log(this); //     Window // Window { postMessage: ƒ, // blur: ƒ, // focus: ƒ, // close: ƒ, // frames: Window, …} function myFunction() { console.log(this); } //   myFunction(); //      Window! // Window { postMessage: ƒ, // blur: ƒ, // focus: ƒ, // close: ƒ, // frames: Window, …} 

Using this inside an object


When this used inside an object, this keyword refers to the object itself. Consider an example. Suppose you create a dog object with methods and in one of its methods refer to this . When this used inside this method, this keyword represents the dog object.

 var dog = { name: 'Chester', breed: 'beagle', intro: function(){   console.log(this); } }; dog.intro(); //      dog       // {name: "Chester", breed: "beagle", intro: ƒ} //    breed:"beagle" //    intro:ƒ () //    name:"Chester" //    __proto__:Object 

This and nested objects


Using this in nested objects can create some confusion. In such situations, it is worth remembering that the this keyword refers to the object in the method of which it is used. Consider an example.

 var obj1 = { hello: function() {   console.log('Hello world');   return this; }, obj2: {     breed: 'dog',     speak: function(){           console.log('woof!');           return this;       }   } }; console.log(obj1); console.log(obj1.hello());  //  'Hello world'   obj1 console.log(obj1.obj2); console.log(obj1.obj2.speak());  //  'woof!'   obj2 

Features of switch functions


Arrow functions do not behave like normal functions. Remember: when you call this in an object method, this keyword corresponds to the object that owns the method. However, this does not apply to switch functions. Instead, this in such functions refers to the global context (the window object). Consider the following code that can be run in the browser console.

 var objReg = { hello: function() {   return this; } }; var objArrow = {   hello: () => this }; objReg.hello(); // ,   ,  objReg objArrow.hello(); //   Window! 

If, perplexed by the issue in question, look at the MDN , there you can find information that the arrow functions have a shorter form of writing than functional expressions and are not tied to their own entities this , arguments , super or new.target . Arrow functions are best suited for using them as ordinary functions rather than as object methods; they cannot be used as constructors.

We will listen to MDN and will not use the arrow functions as methods of objects.

Using this in normal functions


When the normal function is in the global scope, the this keyword used in it will be bound to the window object. Below is an example in which the test function can be viewed as a method of the window object.

 function test() { console.log('hello world'); console.log(this); } test(); // hello world // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} 

However, if the function is executed in strict mode, then this will be written undefined , since in this mode, the default bindings are prohibited. Try running the following example in the browser console.

 function test() { 'use strict'; return this; } console.log( test() ); //  undefined,    Window 

Calling this from a function that was declared outside the object, and then assigned as its method


Consider an example with a dog object already known to us. As a method of this object, you can assign the function chase , declared outside of it. There were no methods in the dog object until we created the foo method, which is assigned the chase function. If you now call the dog.foo method, the chase function will be called. The keyword this , which is accessed in this function, points to the dog object. And the chase function, when trying to call it as a standalone function, will behave incorrectly, since with this approach this will point to a global object, in which there are no properties to which we, in this function, refer to this .

 var dog = { breed: 'Beagles', lovesToChase: 'rabbits' }; function chase() { console.log(this.breed + ' loves chasing ' + this.lovesToChase + '.'); } dog.foo = chase; dog.foo(); //    Beagles loves chasing rabbits. chase(); //      

Keyword new and this


The keyword this is used in the constructor functions used to create objects, as it allows, in a universal way, to work with a variety of objects created using such a function. In JavaScript, there are also standard constructor functions, with the help of which, for example, you can create objects of the Number or String . Such functions, defined by the programmer independently, allow him to create objects, the composition of the properties and methods of which are set by him.

As you already understood, I like dogs, so we describe the constructor function for creating objects of type Dog , containing some properties and methods.

 function Dog(breed, name, friends){   this.breed = breed;   this.name = name;   this.friends = friends;   this.intro = function() {       console.log(`Hi, my name is ${this.name} and I'm a ${this.breed}`);       return this;   }; } 

When a constructor function is called using the keyword new , this in it points to a new object, which, with the help of the constructor, is supplied with properties and methods.

Here's how to work with standard JavaScript constructors.

 var str = new String('Hello world'); /*******    ,     ,  ,     str2 .        ,   JavaScript   ,   ,    ,      .        .  ,  ,  ,   ,           . *******/ var str2 = 'Hello world'; //    , ,  ,        

Now let's work with the Dog function just created.

 //      Dog var chester = new Dog('beagle', 'Chester', ['Gracie', 'Josey', 'Barkley']); chester.intro();        //  Hi, my name is Chester and I'm a beagle console.log(chester);   //  Dog {breed: "beagle", name: "Chester", friends: Array(3), intro: ƒ} 

Here is another example of using constructor functions.

 var City = function(city, state) { this.city = city || "Phoenix"; this.state = state || "AZ"; this.sentence = function() {   console.log(`I live in ${this.city}, ${this.state}.`); }; }; var phoenix = new City(); //     console.log(phoenix); //       phoenix.sentence(); //  I live in Phoenix, AZ. var spokane = new City('Spokane', 'WA'); console.log(spokane); //    spokane.sentence(); //  I live in Spokane, WA. 

About the importance of the new keyword


When the constructor function is called using the new keyword, the this indicates a new object, which, after some work on it, will be returned from this function. The keyword this in this situation is very important. Why? The thing is that with its help it is possible, using a single constructor function, to create many similar objects.

This allows us to scale the application and reduce code duplication. In order to understand the importance of this mechanism, think about how accounts are arranged in social networks. Each account can be an instance of an object created using the Friend constructor function. Each such object can be filled with unique user data. Consider the following code.

 // - var Friend = function(name, password, interests, job){ this.fullName = name; this.password = password; this.interests = interests; this.job = job; }; function sayHello(){  //   ,  ,    this  // console.log(this); return `Hi, my name is ${this.fullName} and I'm a ${this.job}. Let's be friends!`; } //          Friend,    new var john = new Friend('John Smith', 'badpassword', ['hiking', 'biking', 'skiing'], 'teacher'); console.log(john); //    greeting  john john.greeting = sayHello; //     console.log( john.greeting() ); //   ,  sayHello()       console.log( sayHello() ) ; 

Results


In fact, the features of using the this in JavaScript are not limited to the examples described above. So, in the series of these examples it would be possible to include the use of the functions call , apply and bind . Since this material is intended for beginners and is focused on explaining the basics, we do not touch them here. However, if now you have formed an initial understanding of this , then you can easily understand these methods. The main thing is to remember that if something cannot be understood from the first time, do not stop learning, practice, read the materials on the topic that interests you. In one of them, you will definitely get something (some kind of successful phrase, for example) that will help you understand what you didn’t understand before.

Dear readers! Have you had trouble understanding the this keyword in javascript?

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


All Articles