Why does the value of "this" change?

I am learning javascript and I came across doubts. Why in the first example the value of "this" is undefined, but it prints correctly in the second.

example 1:

var myNamespace = { myObject: { sayHello: function() { console.log( "name is " + this.myName ); }, myName: "john" } }; var hello = myNamespace.myObject.sayHello; hello(); // "name is undefined" 

Example 2:

 var myNamespace = { myObject: { sayHello: function() { console.log( "Hi! My name is " + this.myName ); }, myName: "Rebecca" } }; var obj = myNamespace.myObject; obj.sayHello();//"Hi! My name is Rebecca" 

Why the value of the "this" function changes inside the function. What concept am I missing?

+6
source share
2 answers

In the first case, you just get a link to a function on vairable hello and calling it from the global context (window in browsers, global in node), So this becomes what called the function, except for (related functions). You can always explicitly specify the context using function.call or explicitly setting the context of the function using Ecma5 function.bind

 hello.call(myNamespace.myObject); //now you are setting the context explicitly during the function call. 

or just bind it when you get a function reference.

 var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject); //Now no matter where you call it from `this` will point to the context of myObject 

The second case, you call it from the object itself, so this points to the object.

+3
source

In the first case, the implicit this object is a global scope. Since there is no myName in the global myName , you get undefined.

If you need a free function with the correct this , use bind :

 var hello = myNamespace.myObject.sayHello.bind(myNamespace.myObject); 
+1
source

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


All Articles