0

I'm trying to perform an anonymous function with a this-type argument, with the aim that an element of DOM can occupy it.

javascript: (this is dynamically created at run time)

const example = function(this) { return this }

html:

<button onclick="example(this)" ><button>

result:

Uncaught SyntaxError: Unexpected token 'this'

how can I do it?, thanks!

  • 4
    `this` is a special "argument" that you don't list as parameter. The value of `this` is determined by the caller of the function. Not sure what you mean with "doom". See [how does the `this` keyword work](https://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-function) – trincot Jan 17 '22 at 23:22
  • "*a this-type argument, with the aim that an element of doom can occupy it.*" - what? Please show us how you intend to call that `example` function. – Bergi Jan 17 '22 at 23:24
  • @trincot I think "doom" is a typo for "DOM" – Barmar Jan 17 '22 at 23:24
  • Yeah, `this` is a reserved keyword in JS. – BenM Jan 17 '22 at 23:25
  • 2
    @Barmar `` <- *element of doom*. – BenM Jan 17 '22 at 23:26
  • _"an element of doom"_... the `
    ` cannot hold
    – Phil Jan 17 '22 at 23:27
  • edited the question, thanks for answering, sorry for the bad writing, it's my first question and I don't speak much English – Darien correa Jan 17 '22 at 23:47
  • The example function does not suppose to get this, but an argument that will be the this (probably an extended of HTMLElement) – Aviv Ben Shahar Jan 18 '22 at 00:14

1 Answers1

0

As mentioned in the comments, this is a special keyword in JavaScript; when you call an object method, this contains the object that the method was called through.

Just use another variable name.

const example = function(el) { console.log(el.innerText); };
<button onclick="example(this)" >Click me</button>
Barmar
  • 741,623
  • 53
  • 500
  • 612