ThisAssignable

Misconception:

It is legal to assign a value to this.

Incorrect

One can assign to this

Correct

One cannot assign to this

Correction
Here is what's right.

It is impossible to assign a value to this. The following code throws the error SyntaxError: Invalid left-hand side in assignment:

Advanced Usage

In the case of a function, the value of the context available through the keyword this can be changed with the methods method.call, method.bind, and method.apply.

Property .this

The property .this of an object can be assigned normally:

let o = {}
o.this = "Hello"
console.log(o.this)  // "Hello"
o["this"] = "World"
console.log(o.this)  // "World"

In order to enhance the readability of the code, one should avoid to assign the property .this when it is not strictly necessary. The risk of confusing the context with a property can lead to several issues difficult to debug. In the next example we show what could happen if the property .this of an object is assigned:

let obj = {
  this: "Hello World",
  foo: function() { 
    console.log(this.this)
  }
}

obj.foo() // "Hello World"

While the example above is syntactically correct, this.this can potentially confuse anyone reading the code. In fact, there is no reason to call a property this and the code should be refactor with more meaningful names, for example:

let obj = {
  message: "Hello World",
  print: function() {
    console.log(this.message)
  }
}

obj.print() // "Hello World"

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.