How does โ€œthisโ€ work in closure?

I received this document , which says that there is a close:

function addHandler(){ document.getElementById('el').onclick = function(){ this.style.backgroundColor = 'red'; }; } 

So far, this code removes the closure:

 function addHandler() { var clickHandler = function() { this.style.backgroundColor = 'red'; }; (function() { var el = document.getElementById('el'); el.onclick = clickHandler; })(); } 

I do not see how the second solves the closure problem. Why would el.onclick = clickHandler not create a closure? clickHandler this should be done with el .

+6
source share
3 answers

Your example is incorrect. The document you linked indicates that this code block creates a closure that may leak memory (note the variable in the external function):

 function addHandler() { var el = document.getElementById('el'); el.onclick = function() { this.style.backgroundColor = 'red'; }; } 

Both of the examples you provided do not create a closure (or just empty), but they use different methods to avoid this.

Also note that this issue only seems to affect the IE JS engine. Other engines, such as V8 / Chrome, seem to only capture the variables used in internal functions in closure, so I expect that the circular link will not be created in this code example, and even if they were able to handle garbage collection with round links.

+2
source

I do not see how the second solves the closure problem.

This is not true. You still have a close. However, it does not use any private variables.

You can rewrite it to avoid using closure like this:

 var clickHandler = function() { this.style.backgroundColor = 'red'; }; function addHandler() { var el = document.getElementById('el'); el.onclick = clickHandler; } 

You can also change clickHandler to create with a function declaration instead of a function expression.

clickHandler this should be done with el .

No, it is not. If you used closure, you could use el instead of this .

The value of this determined by how the function is called . Closing in the source code has no purpose. When an event handler runs on an element, this will be the element.

+2
source

I donโ€™t think you read the documentation you are referring to correctly. The problem is not with the reference to the closure to 'this', it is if you have variables in the outer scope. Therefore, if you use the variable var el = ... , which will create a closure in IE. But in your first snipe you are not using a variable, so you are good to go.

As mdn says: "There are a number of workarounds for this problem. The simplest thing is not to use the variable el."

+2
source

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


All Articles