【发布时间】:2019-08-09 12:01:06
【问题描述】:
我曾短暂关注过2d game tutorial。它显示了这种对象创建方式:
function component(width, height, color, x, y) {
this.width = width
...
this.method = function(){...}
// instantiate block using class
block = new component(30, 60, "red", 225, 225);
但我也被告知ES6's class functionality,我相信它会做一些非常相似的事情,但更符合其他语言的正式对象创建语法:
class component {
constructor(width, height, color, x, y){
this.width = width
...
}
method(){
...
}
// instantiate block using class
block = new component(30, 60, "red", 225, 225);
这两种方法的功能差异是什么?为什么我要使用一个而不是另一个?
【问题讨论】:
-
@AZ_ 同意这是一个骗局,但没有可接受的答案,现有的答案是......次优的。这是一个更好的问题。
-
类是 JavaScript 中一种非常新的语法。它直到最近才存在。
-
请注意(参考副本)
class语法只是 ES6 编写原型的方法。 -
在这种情况下,类和函数(工厂)都在做同样的事情。引擎盖下的类使用工厂函数来执行(即使我们以经典方式编写也是相同的原型继承)。它只是 Class 关键字使 java-script 中的继承更容易编写(糖语法)。
-
@NineBerry — 类的核心功能只是原型的语法糖,从一开始就在 JS 中。
标签: javascript