Class literals: things ES.next could borrow from Dart

# Axel Rauschmayer (14 years ago)

In many ways, Dart feels less versatile than ECMAScript.next. However, there are two ideas that would make a nice addition to class literals:

  • Named constructors: Without overloading, you need a way to distinguish constructors: new Point.zero()
  • Factory constructors: are a way to mark constructors so that no instance is produced automatically. Then you can return cached instances or instances of a subclasses.

Details: www.dartlang.org/articles/idiomatic-dart

# Quildreen Motta (14 years ago)

We already get factory constructors by default -- by returning an object from the constructor function.

2011/10/10 Axel Rauschmayer <axel at rauschma.de>

# Axel Rauschmayer (14 years ago)

Right. Does that prevent an instance from being created? But it shouldn’t be hard to let a compiler perform that kind of optimization.

# Quildreen Motta (14 years ago)

By specs, a new instance is created and passed as the thisObject' for the constructor function anytime that function is called with thenew' operator. It could be optimised as long as that object is not used.


function Point(x, y) { this.x = x this.y = y console.log(this) return { x: x, y: y } } new Point(1, 1) instanceof Point // => false

This can't be optimised because the `this' object is used. A more real-world use case would be, however:


function Point(x, y) { if (!(this instanceof Point)) return new Point(x, y) this.x = x this.y = y } Point(1, 2) instanceof Point // => true

new Point(1, 2) instanceof Point // => true

Not sure how engines optimise that particular case, I'm not much familiar with JIT techniques either :3

2011/10/10 Axel Rauschmayer <axel at rauschma.de>

# Brendan Eich (14 years ago)

On Oct 10, 2011, at 5:13 AM, Quildreen Motta wrote:

By specs, a new instance is created and passed as the thisObject' for the constructor function anytime that function is called with thenew' operator. It could be optimised as long as that object is not used.

Indeed top engines (tm) do optimize away this specified new object if it's not used.