1

I am confuse about the usage of 'this' in JS.

Take example from w3cshool: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onchange2

<!DOCTYPE html>
<html>
<body>

<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p>

Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">

<script>
function myFunction(val) {
    alert("The input value has changed. The new value is: " + val);
}
</script>

</body>
</html>

If I delete the 'this', it works too, too bad I can't find any tutorial in w3school to differentiate it.

In what situation will 'this' make a different than no 'this'?

P. Lau
  • 165
  • 1
  • 11

3 Answers3

0

"this" refers to the current context of the function or the method you're using it in. So in your example, this refers to the input element because the value of what you typed in is entered from the onchange event, therefore "this.value" will return whatever you type into the input. Here is a related stackoverflow question that has a good answer: What does "this" mean?

Dream_Cap
  • 2,292
  • 2
  • 18
  • 30
0

By now your could have understood that this is available implicitly/explicitly when event handler is assigned to an element. But the example tries to highlight the fact that even whole object this is available and can be passed to the event handler. Have a look at modified code below:

<!DOCTYPE html>
<html>
<body>

<p>Modify the text in the input field, then click outside the field to fire the onchange event.</p>

Enter some text: <input type="text" name="txt" value="Hello" onchange="myFunction(this)">

<script>
function myFunction(val) {
    alert("The input value has changed. The new value is: " + val.value);
    alert("The input value has changed. The new value is: " + val.type);
}
</script>

</body>
</html>
MKR
  • 19,739
  • 4
  • 23
  • 33
0

There is no difference for code that is defined for an on**** HTML attribute. That code will have access to aliases defined for each property of the this object, so you can omit this.. That only works in code that is assigned directly to the on attribute. Those aliases will not exist any more in the function you might call from there.

Demo:

<div onclick="textContent='you clicked!';console.log(textContent)">click me</div>
trincot
  • 317,000
  • 35
  • 244
  • 286