Callable class

by mindplay

JavaScript

// Solution was found here:
// https://stackoverflow.com/a/54511133/283851

// This class is also a function:

class Hey {
  constructor() {
    function hey() {
      return "hey";
    }
    
    this.value = "yo";

		Object.assign(hey, this);
		Object.setPrototypeOf(hey, Object.getPrototypeOf(this));

		return hey;
  }
  
  yo() {
  	return this.value;
  }
}

const hey = new Hey();

console.log(hey()); // it's callable πŸ‘
console.log(hey.yo()); // methods are correctly bound to `this` πŸ‘

console.log(hey instanceof Hey); // it type-checks πŸ‘

// Inheritance works too:

class HeyHey extends Hey {
  constructor() {
  	super();
  }
  
  yoyo() {
    return this.value + "!";
  }
}

const lol = new HeyHey();

console.log(lol()); // it's callable πŸ‘
console.log(lol.yo()); // methods are correctly bound to `this` πŸ‘
console.log(lol.yoyo()); // extension methods are correctly bound to `this` too πŸ‘

console.log(lol instanceof Hey); // it type-checks πŸ‘
console.log(lol instanceof HeyHey); // it type-checks πŸ‘