为什么ES6课堂没有悬挂? [英] Why are ES6 classes not hoisted?

查看:109
本文介绍了为什么ES6课堂没有悬挂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ES6类只是JavaScript现有的基于原型的继承的语法糖 [1] 它会(IMO)有意义的提升它的定义:

Since ES6 classes are just a syntactical sugar over JavaScript's existing prototype-based inheritance [1] it would (IMO) make sense to hoist it's definition:

var foo = new Foo(1, 2); //this works

function Foo(x, y) {
   this.x = x;
   this.y = y;
}

但以下内容将无法正常工作:

But the following won't work:

var foo = new Foo(1, 2); //ReferenceError

class Foo {
   constructor(x, y) {
      this.x = x;
      this.y = y;
   }
}

为什么ES6类不被提升?

Why are ES6 classes not hoisted?

推荐答案


为什么ES6类没有悬挂?

Why are ES6 classes not hoisted?

实际上,他们已经挂起(变量绑定在整个范围内可用),就像 let const - 它们只是没有初始化。

Actually they are hoisted (the variable binding is available in the whole scope) just like let and const are - they only are not initialised.


提升其定义是有意义的

It would make sense to hoist its definition

否。在定义之前使用一个类并不是一个好主意。考虑例子

No. It's never a good idea to use a class before its definition. Consider the example

var foo = new Bar(); // this appears to work
console.log(foo.x)   // but doesn't

function Bar(x) {
    this.x = x || Bar.defaultX;
}
Bar.defaultX = 0;

并将其与

var foo = new Bar(); // ReferenceError
console.log(foo.x);

class Bar {
    constructor (x = Bar.defaultX) {
        this.x = x;
    }
}
Bar.defaultX = 0;

其中会抛出您所期望的错误。这是静态属性,原型mixins,装饰器和一切的问题。另外对于子类化也是非常重要的,当你使用一个没有调整的原型的类时,它在ES5中完全破裂,但是如果一个 extension 尚未初始化。

which throws an error as you would expect. This is a problem for static properties, prototype mixins, decorators and everything. Also it is quite important for subclassing, which broke entirely in ES5 when you used a class with its non-adjusted prototype, but now throws an error if an extended class is not yet initialised.

这篇关于为什么ES6课堂没有悬挂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆