Can You Implement Javascript Class Via Function Expression?

58 views Asked by At

I was tackling this question in leet code:

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.

In javascript, the template for solving the question is:

/**
 * 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)
 */

I was struck by the class template. I'm used to seeing javascript classes more similar to this:

class MapSum {
  constructor() {

  }

  insert(key, value) {

  }

  sum(prefix) {

  }
}

Is the template leetcode provided, considered a class? What kind of class is it? What is it called when you initialize an object via function expression (var MapSum = function() { //....}) ? What are the biggest differences/implications from writing a class that way vs the way I suggested?

1

There are 1 answers

3
Guerric P On BEST ANSWER

The class keyword is actually just syntaxic sugar over prototypal inheritance

This code demonstrates that the two syntaxes are equivalent:

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 is actually just a constructor function, which has a special object named prototype attached to it. Every instance of the class has an internal link to the prototype of the constructor.