为什么不提升 ES6 类? [英] Why are ES6 classes not hoisted?
问题描述
因为 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;
}
但以下方法不起作用:
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.
提升其定义是有意义的
没有.在定义之前使用类从来都不是一个好主意.考虑例子
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;
正如您所期望的那样抛出错误.这是静态属性、原型混合、装饰器和所有东西的问题.这对于子类化也非常重要,当您使用具有未调整原型的类时,它在 ES5 中完全中断,但如果 extend
ed 类尚未初始化,则现在会抛出错误.
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 extend
ed class is not yet initialised.
这篇关于为什么不提升 ES6 类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!