<form action="javascript:alert(this);"> what is "this"?

javascript

Solution

In your example `this` is the global `window` object. Try it yourself:

<form action="javascript:alert(typeof this.setTimeout);">

results in `"function"` (i.e. the global function). Or try:

<form action="javascript:alert(this.nodeType);">

results in `undefined` (i.e. it's not pointing to the form element)*.

The value of `"this"` inside an attribute will only ever be one of two things:

- the global `window` object

- the element itself

The only time `this` points to the element itself is when it is used inside an intrinsic event attribute (the ones that are prefixed with `"on"`, eg `"onclick"`, `"onload"`, etc). These attributes are special: the browser re-scopes `this` to the element the event is firing on, and creates the `event` object (with that name) also available inside the attribute.

If the attribute is not one of the intrinsic events, `"this"` will be the global `window` object.

Footnotes:

* unless of course you happened to have a global var named `"nodeType"`

Problem

When trying to debug what is being submitted, I wrote this. ``` <form action="javascript:alert(this);" ``` - Is it possible to alert what is being submitted? - Here "this" denotes what? I got object in alert box & unable to decide anything out of it. :-)

Original source