Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the context of "this" in this example?

Tags:

Why do these two lines create different values for this?

<div>   <a href="#" id= "li2" onclick="alert(this)"> a link </a>  </div> <p id= "p2" onclick="alert(this)"> a paragraph </p> 

The first one alerts with the file's URI, the second one alerts with the "HTML Paragraph Element". So in other words, the second one context is the DOM element, but the first one is the main context.

I have done A LOT of research on this, and some of them are a bit over my head, so if someone knows the answer, can you dumb it down for me?

like image 308
Sheida Avatar asked Oct 06 '15 18:10

Sheida


People also ask

What is the context of a function?

Context in JavaScript is related to objects. It refers to the object within the function being executed. this refers to the object that the function is executing in. this is determined by how a function is invoked.

What is the context in JS?

In JavaScript, “context” refers to an object. Within an object, the keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of that object. When a function is executed, the keyword “this” refers to the object that the function is executed in.

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 this in arrow function?

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function. Let us take a look at two examples to understand the difference.


1 Answers

In inline JavaScript events, this is the element that the event was triggered on. These are both onclick events, so this is the element you clicked on.

When you use alert(), it converts its parameters to a string. When you convert an <a> element object to a string, you get its href value. When you convert a <p> element to a string, you just get [object HTMLParagraphElement] since it doesn't have a custom toString.

Revalent docs: https://developer.mozilla.org/en-US/docs/Web/API/URLUtils/toString

like image 90
Rocket Hazmat Avatar answered Sep 17 '22 13:09

Rocket Hazmat