Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“this” keyword doesn’t seem to work

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?

like image 398
nope Avatar asked Dec 14 '10 16:12

nope


People also ask

How does the this keyword work?

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.

What is scope of this keyword?

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.

What is this keyword in node JS?

“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 .

What is this keyword in JavaScript stack overflow?

this is a keyword in JavaScript that is a property of an execution context. Its main use is in functions and constructors.


1 Answers

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>
like image 150
Pekka Avatar answered Oct 22 '22 15:10

Pekka