1

I have a form and I am experimenting with formData.. on submit, I created the formData object by passing the 'form' from the DOM as the argument. Now I can pass this argument as e.target, e.currentTarget and it works fine.. but when I use the 'this' keyword, it shows as undefined. Why?

Here's my codepen link.. https://codepen.io/alimbolar/pen/GRWxwzN

const myForm = document.getElementById('myForm');

myForm.addEventListener('submit', (e) => {
  e.preventDefault();

  // uncomment the line below to check 'this' in the console
  // console.log(this)

  const myFormData = new FormData(e.target);
  const dataArray = [...myFormData];
  const data = Object.fromEntries(dataArray);
  console.log(data.name);
  console.log(data.email);
  console.log(data.password)


});
.container form {
  width: 50%;
  margin: auto;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  border: 1px solid black;
  padding: 2em;
  >label,
  button {
    margin-top: 1em;
    text-transform: uppercase;
    font: 1.5em Monospace;
    color: grey;
  }
}
<div class="container">
  <form id="myForm" action="">
    <label for="name">
    Name
  </label>
    <input type="text" id="name" name="name" value="Alim Bolar">

    <label for="email">Email
    </label>
    <input type="email" id="email" name="email" value="alim@alim.com">
    </label>

    <label for="password">Password
  </label>

    <input type="password" id="password" name="password" value="alim123">

    <button type="submit">Submit</button>

  </form>
</div>

you might have to see the results in the console on submit.. please help me understand why 'this' is not equal to e.currentTarget or e.target in this case.

Alim Bolar
  • 479
  • 4
  • 17
  • 1
    Does this answer your question? [JavaScript ecma6 change normal function to arrow function](https://stackoverflow.com/questions/31975772/javascript-ecma6-change-normal-function-to-arrow-function) – Sven Eberth Jun 04 '21 at 16:56
  • 1
    arrow function doesn't bind `this`. Therefore is `this` in you example the `window`. – Sven Eberth Jun 04 '21 at 17:00
  • Thanks @Sven ..:-).. It's so easy to forget this when you use arrow functions.. I'll be more careful from now on.. – Alim Bolar Jun 05 '21 at 01:34

0 Answers0