JS: Define a Class Without Using Keyword class

By Xah Lee. Date: . Last updated: .

Intro

This page shows you how to define a class without using the keyword class 〔see Class〕 , and then other versions without class, without new, without this.

Why

To be able to do that, means deep understanding of the JavaScript prototype object system. Also, it makes many implicit mechanisms explicit, for good functional programing practice.

Using Keyword class

Suppose we want to define a class CC, with a constructor CC(x) that adds a property key kk with value x, and one prototype method ff, and one static method ss.

// Using Keyword class

class CC {
  constructor(x) {
    this.kk = x;
  }

  static ss(x) {
    return "ss " + x.toString();
  }

  ff(x) {
    return "ff " + x.toString();
  }
}

// HHHH------------------------------


console.log(CC.ss(3) === "ss 3");

const jj = new CC(4);

console.log(jj.hasOwnProperty("kk"));
console.log(jj.kk === 4);

console.log(jj.ff(2) === "ff 2");

console.log(Reflect.getPrototypeOf(jj) === CC.prototype);
console.log(jj.constructor === CC);

Without Keyword class

function CC(x) {
  this.kk = x;
}

CC.ss = function (x) {
  return "ss " + x.toString();
};

CC.prototype.ff = function (x) {
  return "ff " + x.toString();
};

// HHHH------------------------------

console.log(CC.ss(3) === "ss 3");

const jj = new CC(4);

console.log(jj.hasOwnProperty("kk"));
console.log(jj.kk === 4);

console.log(jj.ff(2) === "ff 2");

console.log(Reflect.getPrototypeOf(jj) === CC.prototype);
console.log(jj.constructor === CC);

Without Keywords class, new, this

This makes it easier to see what class is doing, because all parent child relationship are explicit.

const CC = ((x) => {
  const xthis = {};
  Reflect.setPrototypeOf(xthis, CC.prototype);

  xthis.kk = x;

  return xthis;
});

CC.ss = function (x) {
  return "ss " + x.toString();
};

CC.prototype = {
  ff: function (x) {
    return "ff " + x.toString();
  },
  constructor: CC,
};

// HHHH------------------------------

console.log(CC.ss(3) === "ss 3");

const jj = CC(4);

console.log(jj.hasOwnProperty("kk"));
console.log(jj.kk === 4);

console.log(jj.ff(2) === "ff 2");

console.log(Reflect.getPrototypeOf(jj) === CC.prototype);
console.log(jj.constructor === CC);

Without Keywords class, new, this, function

const CC = ((x) => {
  const xthis = {};
  Reflect.setPrototypeOf(xthis, CC.prototype);

  xthis.kk = x;

  return xthis;
});

CC.ss = (x) => {
  return "ss " + x.toString();
};

CC.prototype = {
  ff: ((x) => {
    return "ff " + x.toString();
  }),
  constructor: CC,
};

// HHHH------------------------------

console.log(CC.ss(3) === "ss 3");

const jj = CC(4);

console.log(jj.hasOwnProperty("kk"));
console.log(jj.kk === 4);

console.log(jj.ff(2) === "ff 2");

console.log(Reflect.getPrototypeOf(jj) === CC.prototype);
console.log(jj.constructor === CC);

JavaScript, Constructor, Class