【问题标题】:Why would I create an object with 'class' instead of 'function'? [duplicate]为什么我要创建一个带有“类”而不是“功能”的对象? [复制]
【发布时间】: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


【解决方案1】:

类是编写构造函数的新方法。在引擎盖下,您的代码转换为构造函数。

例如,你有一个班级:

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 所说:

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

另外:

  • 类可以有构造函数构造函数,函数是构造函数。
  • 继承方式之间的差异。类使用关键字extends,函数使用prototype关键字
  • 如何定义私有字段。类使用# 符号。例如:#property 和函数:function Container(param) { this.member = param; var secret = 3; // private memeber var that = this; // private memeber }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    相关资源
    最近更新 更多