The other constructors: Object.create() and String.fromCharCode()

Dmitry A. Soshnikov dmitry.soshnikov at gmail.com
Sun Jun 5 11:46:54 PDT 2011


On 05.06.2011 22:00, Peter Michaux wrote:
> ES has "new Constructor()" as its basic syntax for construction. This
> means that if other constructors are also beneficial that the syntax
> to call them is inconsistent. For example, ES3 had the
> "String.fromCharCode" and ES5 added "Object.create".

This is a basic idea of class-factory-methods, i.e. when an instance is 
created not directly by specified arguments, but with prior actions 
applied on the different kind of argument(s) passed to the factory. That 
is (pseudo-code):

class Point
   new: (x, y) ->
     this.x = x
     this.y = y
end

Point.fromString(s) = ->
   Point.new(...s.split(":"))
end

a = Point.new(1, 2)
b = Point.fromString("1:2")

and this kind of methods are placed on constructors (the main idea which 
I'm saying, is that `String.fromCharCode` isn't here because of 
inconsistency, but because of it's such a class-method, which is 
constructor of an instance).

>   These are both
> constructors of sorts. Would it be possible to add "String.new" etc so
> that construction is consistent?
>

Sure, I also used such a notation with `.new` in my experiments. BTW, 
this is the approach used in Ruby too -- `new` is just (class-) method 
there.

> Unfortunately Date.now, Date.parse, Date.UTC don't return Date objects
> as they would be elegant cases of being other constructors.
>
> Yes in order to get consistent syntax, host objects would need to
> implement the static "new" method.
>

It can be done with a simple library though -- just wrappers for all 
kind of cases.

> (I remember the idea of being able to write "String.new" rather than
> having to write "String['new']" was discussed in the past. I don't
> know if keywords as bare object keys are allowed in ECMAScript but it
> seems to work in Firefox.)
>

Yes, it's possible per ES5.

Dmitry.


More information about the es-discuss mailing list