在玩完ES6之后,我真的开始喜欢可用的新语法和功能,但是我确实对类有疑问。新的ES6类只是旧原型模式的语法糖吗?还是幕后还有更多事情要做?即:class Thing { //... classy stuff doStuff(){}}vs:var Thing = function() { // ... setup stuff};Thing.prototype.doStuff = function() {}; // etc
3 回答
HUWWW
TA贡献1874条经验 获得超12个赞
是。但是它们更加严格。
您的示例有两个主要区别。
首先,使用类语法,没有new关键字就无法初始化实例。
class Thing{}
Thing() //Uncaught TypeError: Class constructor Thing cannot be invoked without 'new'
var Thing = function() {
if(!(this instanceof Thing)){
return new Thing();
}
};
Thing(); //works
第二个是,使用类语法定义的类是块作用域的。类似于使用let关键字定义变量。
class Thing{}
class Thing{} //Uncaught SyntaxError: Identifier 'Thing' has already been declared
{
class Thing{}
}
console.log(Thing); //Uncaught ReferenceError: Thing is not defined
编辑
正如@zeroflagL在他的评论中提到的那样,也不会悬挂类声明。
console.log(Thing) //Uncaught ReferenceError: Thing is not defined
class Thing{}
添加回答
举报
0/150
提交
取消
