function log(this) {
console.log(this);
}
It throws the error Unexpected token this
. So why doesn't JavaScript accept this
as an argument?
function log(this) {
console.log(this);
}
It throws the error Unexpected token this
. So why doesn't JavaScript accept this
as an argument?
this
is a reserved keyword so it can't be used as a variable name.
If you want to override the this
value for a function, you can use call
or apply
.
function log() {
console.log(this);
}
log.apply({ custom: "this value" });
this
has special meaning in the language. It's an identifier, but can only be defined automatically in specific situations, never explicitly by the developer.
Other identifiers that are automatically defined can still be defined by the developer, like arguments
, undefined
and window
, though it should be avoided in most cases.
To add clarity, in programming an identifier is a label used by a programmer to reference a value.
In JS, this
is indeed a keyword, which, according to ECMAScript semantics, prevents it from being explicitly declared as an identifier. This does not mean that it isn't an identifier at all, which it clearly is since it will always let the programmer reference a value.
So something being a keyword does not mean that it isn't an identifier. It does mean though that in JS, you don't have the option of explicitly declaring an identifier with that name, though other languages do sometimes allow this.