Javascript 为什么要用';类别';而不是';函数';?

Javascript 为什么要用';类别';而不是';函数';?,javascript,Javascript,我曾短暂地关注过一个问题。它显示了这种类型的对象创建: 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); 但我也听说过,我相信这会做一些非常类似的事情,但更符合其

我曾短暂地关注过一个问题。它显示了这种类型的对象创建:

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);
但我也听说过,我相信这会做一些非常类似的事情,但更符合其他语言的正式对象创建语法:

class component {
    constructor(width, height, color, x, y){
        this.width = width
        ...
    }

   method(){
       ...
   }

// instantiate block using class
block = new component(30, 60, "red", 225, 225);

这两种方法的功能区别是什么?为什么我要使用一个而不是另一个呢?

类是编写构造函数的新方法。在后台,您的代码被转换为构造函数

例如,你有一门课:

class Person {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    getFullName() {
        return this.firstName + " " + this.lastName ;
    }
}
在引擎盖下,您将具有构造函数功能:

function Person(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
}

Person.prototype.getFullName()= function () {
    return this.firstName + " " + this.lastName ;
}
正如mdn所说:

类实际上是“特殊函数”,正如您可以定义的那样 函数表达式和函数声明,类语法 两个组件:类表达式和类声明

此外:

  • 类可以有构造函数,函数可以有构造函数
  • 继承方式之间的差异。类使用关键字
    扩展
    ,函数使用
    原型
    关键字
  • 如何定义私有字段。类使用
    #
    符号。例如:
    #属性
    和函数:
    函数容器(param){
    this.member=param;
    var secret=3;//私有成员
    var that=this;//private memeber
    }

@AZ_uu同意这是一个骗局,但没有公认的答案,现有的答案是。。。次优。这是一个更好的问题。类在JavaScript中是一种非常新的语法。它直到最近才出现。请注意(参考副本),
class
语法只是ES6编写原型的方法。在这种情况下,类和函数(工厂)都在做同样的事情。类使用工厂函数来执行(即使我们以经典方式编写,也使用相同的原型继承)。它的just Class关键字使java脚本中的继承更容易编写(sugar语法)。@NineBerry-类的核心功能只是从一开始就在JS中的原型的语法sugar。