javascript: what's the difference between a function and a class

Viewed 34692

I am wondering what's the difference between function and class. Both using the keyword function, is there obvious distinction between those two?

7 Answers

Difference between a constructor function and class

The class keyword in javascript is very similar to a constructor function in the following manner:

  • They are both using javascript's prototypal inheritance system
  • They are both used to create objects with the following syntax: new myObj(arg1, arg2)

Constructor functions and classes are very alike can often be used interchangeably based on preference. However, javascript's private fields to classes is functionality which cannot be implemented by constructor functions (without scope hacks)

Example:

class PersonClass {
  constructor(name) {
    this.name = name;
  }
  
  speak () { console.log('hi'); }
}

console.log(typeof PersonClass); 
// logs function, a class is a constructor function under the hood.

console.log(PersonClass.prototype.speak);
// The class's methods are placed on the prototype of the PersonClass constructor function

const me = new PersonClass('Willem');

console.log(me.name); 
// logs Willem, properties assinged in the constructor are placed on the newly created object


// The constructor function equivalent would be the following:
function PersonFunction (name) {
  this.name = name;
}

PersonFunction.prototype.speak = function () { console.log('hi'); }

Class

A class declaration is scoped to its containing block. It is an error to declare a class name twice in the same block. Class definition are not hoisted.

Functions

Function declaration is block scope in strict mode.

The below table summarize the difference between class and function enter image description here

Related