JS: Define a Class Without class

By Xah Lee. Date: . Last updated: .

here's how to define a class without keywords class, new, this, function.

// first, here's a normal way to define a class

class Dog {
 constructor(x) {
  this.legs = x;
 }

 static bark(x) {
  return x;
 }

 color(x) {
  return x;
 }
}

// s------------------------------
// define the same class without Keywords: class, new, this, function

const Dog2 = (x) => {
 const resultObj = Object.create(Dog2.prototype);
 resultObj.legs = x;
 return resultObj;
};

Dog2.bark = (x) => {
 return x;
};

Dog2.prototype = {
 color: (x) => {
  return x;
 },
 constructor: Dog2,
};

// s------------------------------
// test

console.assert(Dog.bark("woof") === "woof");

const xobj = new Dog(4);

console.assert(Object.hasOwn(xobj, "legs"));
console.assert(xobj.legs === 4);

console.assert(xobj.color("white") === "white");

console.assert(Reflect.getPrototypeOf(xobj) === Dog.prototype);
console.assert(xobj.constructor === Dog);

// s------------------------------

console.assert(Dog2.bark("woof") === "woof");

const xobj2 = Dog2(4);

console.assert(Object.hasOwn(xobj2, "legs"));
console.assert(xobj2.legs === 4);

console.assert(xobj2.color("white") === "white");

console.assert(Reflect.getPrototypeOf(xobj2) === Dog2.prototype);
console.assert(xobj2.constructor === Dog2);