Approaching class initializers differently?

# Axel Rauschmayer (14 years ago)

I wonder if we could get most of the benefits of class initializers, but approach the issue from the object side. I have no intent of launching a competing proposal (given that I don’t understand all the issues that are involved), but just wanted to put the idea out there.

= Parameterized object literals (POLs) =

Parameterized object literals are a more stylized version of functions that return object literals. If they assign a prototype, they can be used to implement types.

function f(a,b) {...} becomes object f(a,b) {...}
function(a,b) {...} becomes object(a,b) {...}

object Point(x,y) { proto: { dist: function() { return Math.sqrt((xx)+(yy)); } }, x: x, y: y, }

object Colored(color) { proto: { describe: function() { return "Color: "+this.color; } }, color: color }

// Not multiple inheritance (linear chain of types!) object ColoredPoint(x, y, color) extends Point(x,y), Colored(color) { }

Comments:

  • proto is a pseudo-property that can only be set once.
  • Getters and setters work like in object literals.
  • Still needed: defining property attributes (writable, configurable, enumerable) directly in object literals.
  • Possible: init() method that performs additional computations.

Algorithm for type chaining:

  • Collect all prototypes (if any) and chain (copies of) them
    • Assign the combined prototype to proto (no prototypes => do nothing)
  • Chain the parameterized object literals in a similar manner

Similar to POLs: class initializers [1]:

  • Main difference: POLs approach the issue from the object side and increase the declarativeness of what would be the new() method in class initializers.
  • Advantage: there is no need to introduce the concept of classes in JavaScript.

[1] strawman:obj_initialiser_class_abstraction