为什么是“这个"?在ES6类中不是隐式的? [英] Why is "this" in an ES6 class not implicit?
问题描述
我知道ES6解决了ES5中this
关键字存在的许多问题,例如箭头函数和类.
I know that ES6 solved a lot of problems that existed with the this
keyword in ES5, such as arrow functions and classes.
我的问题与在ES6类的上下文中this
的用法以及为什么必须显式编写它有关.我最初是一名Java开发人员,并且来自以下几行代码很自然的世界.
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);
}
}
编译器将始终引用字段myName
的值,除非编译器具有在方法范围内定义的名称为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.
但是,一旦我们将此代码转换为ES6:
However, once we convert this code to ES6:
class Person {
constructor() {
this.myName = "Heisenberg";
}
sayMyName() {
console.log(`My name is ${myName}`);
}
}
这将不起作用,它将抛出一个Uncaught ReferenceError: myName is not defined
.解决此问题的唯一方法是抛出一个明确的this
引用:
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}`)
我了解在构造函数中需要this
的需求,因为ES6类不允许在构造函数之外定义字段,但是我不明白为什么Javascript引擎不能(或不会, (因为该标准)在sayMyName
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
推荐答案
也许我不会直接回答您的问题,但是我将尝试指导您考虑JS class
关键字的方式.
Maybe I will not directly answer your question, but I'll try to direct the way you should think about JS class
keyword.
在封面下没有任何魔术.基本上,这是自JavaScript诞生以来对原型继承的一种语法糖.
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.
之所以需要显式编写this
,是因为在JS中,它始终是上下文相关的,因此您应该引用确切的对象.阅读更多.
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.
这篇关于为什么是“这个"?在ES6类中不是隐式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!