I am trying to understand how the 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 it doesn't work, can anyone explain why?
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
If a function which includes 'this' keyword, is called from the global scope then this will point to the window object. Learn about global and local scope here. In the above example, a function WhoIsThis() is being called from the global scope. The global scope means in the context of window object.
“this” Refers to a Global Object The window object is the global object in the case of the browser. And in a NodeJS environment, a special object called global will be the value of this .
this is a keyword in JavaScript that is a property of an execution context. Its main use is in functions and constructors.
this
exists only in the scope of the onclick
event itself. It is not bound automatically to other functions.
Pass it on like this:
function click(element){
element.innerHTML="changed";
}
and the html:
<button id="clicker" onclick="click(this)" >Click me</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With