📜 ⬆️ ⬇️

The javascript this keyword is learning to define the context in practice.

At the request of some readers decided to write a topic about the context in javascript. Newbies javascript often do not understand the meaning of this keyword in javascript. This topic will be interesting not only for beginners, but also for those who just want to refresh this aspect in memory. See the example below. If you find it difficult to answer the question “what will be displayed in the log” at least in one of the items or you just want to see the answers - welcome under cat.

var f = function() { this.x = 5; (function() { this.x = 3; })(); console.log(this.x); }; var obj = {x: 4, m: function() { console.log(this.x); }}; f(); new f(); obj.m(); new obj.m(); f.call(f); obj.m.call(f); 


Answers for the impatient
3
five
four
undefined
five
five


1. Theory


Unlike many other programming languages, the javascript keyword this does not bind to an object, but depends on the context of the call. To simplify the understanding, we will consider examples applied to the browser, where the global object is a window.
')
1.1. Simple function call

 function f() { console.log(this === window); // true } f(); 


In this case, this inside the function f is equal to the global object (for example, in the browser it is a window , in Node.js it is global ).

Self-invoking functions work in exactly the same way.

 (function () { console.log(this === window); // true })(); 


1.2. In the constructor

 function f() { this.x = 5; console.log(this === window); // false } var o = new f(); console.log(ox === 5); // true 


When a function is called using the new keyword, the function acts as a constructor, and in this case this refers to the object being created.

1.3. In the object method

 var o = { f: function() { return this; } } console.log(of() === o); // true 


If the function is run as a property of an object, then this will contain a link to this object. It does not matter where the function came from in the object, the main thing is how it is called, namely which object is in front of the function call:

 var o = { f: function() { return this; } } var o2 = {f: of}; console.log(of() === o);//true console.log(o2.f() === o2);//true 


1.4. Methods apply, call

The apply and call methods allow you to set the context for the function being performed. The difference between apply and call is only in the way parameters are passed to the function. The first parameter of both functions determines the execution context of the function (what this will be equal to).

The difference in apply / call
 function f(a,b,c) { return a * b + c; } f.call(f, 1, 2, 3); //    ; var args = [1,2,3]; f.apply(f, args); // //     ; //      <b>f</b>   a = 1, b = 2, c = 3; 



Examples:

 function f() { } f.call(window); // this   f     window f.call(f); //this  f    f 


Smarter:

 function f() { console.log(this.toString()); // 123 } f.call(123); // this   f     Number   123 


2. We disassemble the task


Let us apply this knowledge to the problem given at the beginning of the topic. Again, for simplicity, we will consider examples in relation to the browser, where the global object is a window.

2.1. f ()

 var f = function() { //  f      - f(), //  this     this.x = 5; // window.x = 5; //   1.1  ,     this      (function() { this.x = 3; // window.x = 3 })(); console.log(this.x); // console.log(window.x) }; 


Result: 3

2.2. new f ();

 var f = function() { //  f      new, //  this     (   object) this.x = 5; // object.x = 5; //   1.1  ,     this     (function() { this.x = 3; // window.x = 3 })(); console.log(this.x); // console.log(object.x) }; 

Result: 5

2.3. obj.m ();

 var obj = {x: 4, m: function() { //   1.3 ,  this === obj, console.log(this.x); // console.log(obj.x) } }; 

Result: 4

2.4. new obj.m ();

 var obj = {x: 4, m: function() { //   1.2 ,  this      //         this.x,   - undefined console.log(this.x); } }; 


Result: undefined

2.5. f.call (f);

 var f = function() { //  f     call //    call    ( ) f,  //  this   f this.x = 5; // fx = 5; //   1.1  ,     this     (function() { this.x = 3; // window.x = 3 })(); console.log(this.x); // console.log(fx) }; 

Result: 5

2.6. obj.m.call (f);

 var obj = {x: 4, m: function() { //      call //     f //  this    f //    fx    5,   5 console.log(this.x); // console.log(fx) } }; 


Result: 5

Attention: If this example is considered separately from the others, then the log will contain not 5, but undefined. Try to carefully analyze the example and explain the behavior.
 var f = function() { this.x = 5; (function() { this.x = 3; })(); console.log(this.x); }; var obj = {x: 4, m: function() { console.log(this.x); }}; obj.m.call(f); 


Instead of conclusion


Answers all together
3
five
four
undefined
five
five


In the article I tried to describe how the this keyword works in javascript. In the near future, I will most likely write an article that describes why you need to know these subtleties (for example, jQuery.proxy)

PS If you notice errors / inaccuracies or want to clarify / add something - write in the LAN, I will correct it .

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


All Articles