你能通过函数表达式实现 Javascript Class 吗?

Can You Implement Javascript Class Via Function Expression?

我在 leet 代码中解决了这个问题:

Implement the MapSum class:

MapSum() Initializes the MapSum object. void insert(String key, int val) Inserts the key-val pair into the map. If the key already existed, the original key-value pair will be overridden to the new one. int sum(string prefix) Returns the sum of all the pairs' value whose key starts with the prefix.

在javascript中,解题模板为:

/**
 * Initialize your data structure here.
 */
var MapSum = function() {

};

/** 
 * @param {string} key 
 * @param {number} val
 * @return {void}
 */
MapSum.prototype.insert = function(key, val) {

};

/** 
 * @param {string} prefix
 * @return {number}
 */
MapSum.prototype.sum = function(prefix) {

};

/** 
 * Your MapSum object will be instantiated and called as such:
 * var obj = new MapSum()
 * obj.insert(key,val)
 * var param_2 = obj.sum(prefix)
 */

我对 class 模板感到震惊。我习惯看到 javascript class 更像这个:

class MapSum {
  constructor() {

  }

  insert(key, value) {

  }

  sum(prefix) {

  }
}

是否提供了leetcode模板,算是class?什么样的 class 是什么?通过函数表达式 (var MapSum = function() { //....}) 初始化对象时调用什么? 以这种方式写 class 与我建议的方式相比,最大的 differences/implications 是什么?

class 关键字实际上只是 prototypal inheritance

的语法糖

这段代码演示了两种语法是等价的:

class MapSum {
  constructor() {
    
  }
    
  insert(key, value) {
    
  }
    
  sum(prefix) {
    
  }
}

console.log(typeof MapSum); // function (actually the constructor)
console.log(MapSum.prototype.insert); // function
console.log(MapSum.prototype.sum); // function

A class 实际上只是一个构造函数 function,它附加了一个名为 prototype 的特殊对象。 class 的每个实例都有一个构造函数原型的内部 link。