"this" keyword does not work

I am trying to understand how this keyword works in JavaScript, and I made this script:

 function click(){ this.innerHTML="changed"; } 

Used in this HTML:

 <button id="clicker" onclick="click()" >Click me</button> 

But this will not work, can someone explain why?

+4
source share
4 answers

this only exists within the onclick event itself. It is not automatically associated with other functions.

Skip it as follows:

 function click(element){ element.innerHTML="changed"; } 

and html:

 <button id="clicker" onclick="click(this)" >Click me</button> 
+13
source

The click function does not know about 'this'. Change it to:

 function click(elemenet){ element.innerHTML="changed"; } 

and

 <button id="clicker" onclick="click(this)" >Click me</button> 
+3
source

Your question seems to be about the meaning of this . In the built-in handler, this will represent window . You can set this value with .call() so that it gives the desired value.

Example: http://jsfiddle.net/patrick_dw/5uJ54/

 <button id="clicker" onclick="click.call(this)" >Click me</button> 

Your click this method will this have a <button> element.

The reason is because your inline attribute is wrapped in a function that itself has an element context. But this does not actually call your function from this context. By executing click() , it looks like this:

 function onclick(event) { click(); } 

Your function is called against any particular object, so window implied. Performing:

 <button id="clicker" onclick="click.call( this )" >Click me</button> 

... You'll get:

 function onclick(event) { click.call( this ); } 

Providing the desired context. You can also pass an event object:

 <button id="clicker" onclick="click.call( this, event )" >Click me</button> 

... so you end up with:

 function onclick(event) { click.call( this, event ); } 

So, now in your click() function you will have event , as you would expect.

In addition, you may experience problems using click as the function name. I would change it.

+2
source

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


All Articles