Why does “this” change when passing an argument to a function as a string or a link?

Take a look at this ...

var a = { b: function() { console.log(this); } } // Example 1 ab(); // a // Example 2 eval('ab()'); // a // Example 3 setTimeout('ab()', 100); // a // Example 4 setTimeout(ab, 100); // Window // Example 5 var c = ab; c(); // Window 

jsFiddle .

Assuming the expected result is what I expected ...

Example 1

When b() called, the Object property, this becomes the Object property, here it is the parent of a . It gives the expected result.

Example 2

eval() intended to take its execution context where it is called, in this case window . It also gives the expected result.

Example 3

When passing a string to setTimeout() , I would suggest that it runs something very similar to eval() . It also gives the expected result.

Example 4

this becomes window in this example. It interests me.

Example 5

Here, this becomes window , because c parent of the window .

  • When passing only a reference to a function (for example, ab ), will this always be window when called with () ?

  • The only way to save it this as a , to pass it as a string in setTimeout() / setInterval() ?

Thanks.

+6
source share
2 answers

When passing only function references (e.g. ab), will it always be a Window when called with ()?

Yes

Is this the only way to save it as a, to pass it as a string in setTimeout () / setInterval ()?

Not. Instead, create a new function.

 setTimeout(function() { ab() }, 100); 
+7
source

Developers are often confused about the javascript of this keyword. The most important thing to remember is that it is provided by challenge.

In the fourth example:

 // Example 4 setTimeout(ab, 100); // Window 

the first argument is a function reference, so it is called without any "parent" object. Since the call does not provide an object, it is set to window .

Your comment on example 5:

Here it becomes a Window because the parent is Window.

really wrong. Since a function call does not provide an object for use as this , it is set to window (which is the default when the object is not provided).

This is the only way to save this. How to pass it as a string to setTimeout () / setInterval ()?

Not. Besides calling it as an object property, you can use call or apply :

 var x = ab; x.call(a); 
0
source

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


All Articles