DavidBruant / ECMAScript-regrets

Learning from mistakes of the past
55 stars 2 forks source link

special behaviours of native constructors #28

Open michaelficarra opened 11 years ago

michaelficarra commented 11 years ago

Certain specified behaviours of native constructors can't be simulated, such as setting the [[Class]] and [[PrimitiveValue]] properties. This prevents us from constructing an instance of these constructors with a nondeterministic number of arguments (as you would with apply normally). Here's how we can try to instantiate Date the way we would any other constructor with a dynamic set of arguments:

+function(ctor, args){
  var tmpCtor = function(){};
  tmpCtor.prototype = ctor.prototype;
  var obj = new tmpCtor;
  var result = ctor.apply(obj, args)
  return Object(result) === result ? result : obj;
}(Date, [1990, 01, 01]);

You would expect this to produce 633852000000, but because it doesn't have a [[PrimitiveValue]], it throws the error

TypeError: this is not a Date object.
    at Date.valueOf (native)
    [...]