I know that ES6 solved a lot of problems that existed with the this
keyword in ES5, such as arrow functions and classes.
My question relates to the usage of this
in the context of an ES6 class and why it has to be written explicitly. I was originally a Java developer and I come from a world where the following lines of code were perfectly natural.
class Person {
private String myName;
public Person() {
myName = "Heisenberg";
}
public void sayMyName() {
System.out.println("My name is " + myName);
}
}
The compiler will always refer to the value of the field myName
, unless it has a local variable with the name myName
defined in the scope of the method.
However, once we convert this code to ES6:
class Person {
constructor() {
this.myName = "Heisenberg";
}
sayMyName() {
console.log(`My name is ${myName}`);
}
}
This won't work and it will throw an Uncaught ReferenceError: myName is not defined
. The only way to fix this is to throw in an explicit this
reference:
console.log(`My name is ${this.myName}`)
I understand the need for this
in the constructor since ES6 classes don't allow your fields to be defined outside of the constructor, but I don't understand why the Javascript engines can't (or won't, because of the standard) do the same as Java compilers can in the case of sayMyName
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
When es6 was released, it presented a wonderful new way to deal with the this keyword. It changed the this binding to a pattern called lexical scoping. The simplest way to describe lexical scoping is that the inner function (or any nested functions) have access to variables which are declared in it's outer scope.
In this course, Object-oriented Programming in JavaScript - ES6, you will learn this new syntax and create many different kinds of classes. You'll learn all the features of JavaScript classes including working with constructors, prototypes, inheritance, and simulating public, private, and static members.
To reiterate, ES6 classes are primarily syntactic sugar casting prototypal delegation (which is lesser known) in the guise of class inheritance (which is widely known).
Maybe I will not directly answer your question, but I'll try to direct the way you should think about JS class
keyword.
Under the cover there is no magic about it. Basically it's a syntatic sugar over prototypal inheritance that was since the beginning of JavaScript.
To read more about classes in JS click here and here.
As of why you need explicitly write this
is that because in JS it's always context sensitive, so you should refer to exact object. Read more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With